2

Given below is my java code which is a part of a sample webservice:

@Override
    public void filter(ContainerRequestContext requestContext)
    {
        Method method = resourceInfo.getResourceMethod();
        //Access allowed for all
        if( ! method.isAnnotationPresent(PermitAll.class))
        {
            //Access denied for all
            if(method.isAnnotationPresent(DenyAll.class))
            {
                requestContext.abortWith(ACCESS_FORBIDDEN);
                return;
            }

            //Get request headers
            final MultivaluedMap<String, String> headers = requestContext.getHeaders();

            //Fetch authorization header
            final List<String> authorization = headers.get(AUTHORIZATION_PROPERTY);

            //If no authorization information present; block access
            if(authorization == null || authorization.isEmpty())
            {
                requestContext.abortWith(ACCESS_DENIED);
                return;
            }

            //Get encoded username and password
            final String encodedUserPassword = authorization.get(0).replaceFirst(AUTHENTICATION_SCHEME + " ", "");

            //Decode username and password
            String usernameAndPassword = new String(Base64.decode(encodedUserPassword.getBytes()));;

            //Split username and password tokens
            final StringTokenizer tokenizer = new StringTokenizer(usernameAndPassword, ":");
            final String username = tokenizer.nextToken();
            final String password = tokenizer.nextToken();

            //Verifying Username and password
            System.out.println(username);
            System.out.println(password);

          //Is user valid?
            if( ! isUserAllowed(username, password))
            {
                requestContext.abortWith(ACCESS_DENIED);
                return;
            }
        }
    }

And my swift code to get the response is :

let headers = [
        "authorization": "Basic YWRtaW46YWRtaW4=",
        "cache-control": "no-cache"
    ]
    let parameters = ["username" : "admin","password" : "admin"]


    let request = NSMutableURLRequest(URL: NSURL(string: "http://192.168.10.229:8080/JerseyDemos/rest/employees")!,
                                      cachePolicy: .UseProtocolCachePolicy,
                                      timeoutInterval: 60.0)
    request.HTTPMethod = "GET"
    //request.allHTTPHeaderFields = headers
    do {
        request.HTTPBody = try! NSJSONSerialization.dataWithJSONObject(parameters, options: [])
    }
    request.addValue("application/json", forHTTPHeaderField: "Content-Type")
    request.addValue("application/json", forHTTPHeaderField: "Accept")
    let session = NSURLSession.sharedSession()
    let dataTask = session.dataTaskWithRequest(request, completionHandler: { (data, response, error) -> Void in
        if (error != nil) {
            print(error)
        } else {
            let httpResponse = response as? NSHTTPURLResponse
            print(httpResponse)
        }
    })

    dataTask.resume()

But this is not working well. I am getting below error :

Optional(Error Domain=NSURLErrorDomain Code=-1017 "cannot parse response" UserInfo={NSErrorFailingURLStringKey=http://192.168.10.229:8080/JerseyDemos/rest/employees, _kCFStreamErrorCodeKey=-1, NSErrorFailingURLKey=http://192.168.10.229:8080/JerseyDemos/rest/employees, NSLocalizedDescription=cannot parse response, _kCFStreamErrorDomainKey=4, NSUnderlyingError=0x145319e0 {Error Domain=kCFErrorDomainCFNetwork Code=-1017 "(null)" UserInfo={_kCFStreamErrorDomainKey=4, _kCFStreamErrorCodeKey=-1}}})

How can I make this working? The java service is working fine. I checked it with Postman.

2
  • 1
    You might be in that use case: stackoverflow.com/a/27724627/2914850. Commented Nov 23, 2016 at 13:17
  • @Zico Thanks. That link helped me. Commented Nov 24, 2016 at 3:59

2 Answers 2

0

Starting from ios 10 you should use https urls only.

You need to add ssl certificate to your java server.

Sign up to request clarification or add additional context in comments.

1 Comment

we can use http urls in iOS 10 by using <key>NSAppTransportSecurity</key> <dict> <key>NSAllowsArbitraryLoads</key> <true/> </dict> in info.plist
0

Found the solution from the link Zico has provided. The solution is added below :

let parameters = ["username" : "admin","password" : "admin"]
    let parameterString = parameters.stringFromHttpParameters()
    let request = NSMutableURLRequest(URL: NSURL(string: "http://192.168.10.229:8080/JerseyDemos/rest/employees?\(parameterString)")!,
                                      cachePolicy: .UseProtocolCachePolicy,
                                      timeoutInterval: 60.0)
    request.HTTPMethod = "GET"
    request.addValue("application/json", forHTTPHeaderField: "Content-Type")
    request.addValue("application/json", forHTTPHeaderField: "Accept")
    let session = NSURLSession.sharedSession()
    let dataTask = session.dataTaskWithRequest(request, completionHandler: { (data, response, error) -> Void in
        if (error != nil) {
            print(error)
        } else {
            let httpResponse = response as? NSHTTPURLResponse
            print(httpResponse)
        }
    })

    dataTask.resume()

I hope this will help other people here.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.