简体   繁体   中英

NSURLSession get response from Servlet

Currently, I am using NSURLSession and HTTPPost method to upload data to Java servlet. The java servlet will parse the data received and update it into database.

let dataTest:NSData = dao.readStringFromDb().data
let request = NSMutableURLRequest(URL: NSURL(string: urlSubmit)!)
    request.HTTPMethod = "POST"
    request.addValue("multipart/form-data", forHTTPHeaderField: "Accept")
    request.HTTPBody = dataTest
let session = NSURLSession.sharedSession()
let task    = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
    print("Response: \(response)")})
    task.resume()
}

During update process (in Java), different status flags are updated into DB based on different conditions. Now, my requirement is to get that status returned from the web server and show locally.

I am aware that I can use HTTPGet method again, pass the key value and get the status flag.

I am trying to explore if there are any callback handlers available to use with java servlets like the one available in javascript.

Any suggestions would be highly helpful.

Regards.

You already implemented the call back to handle the response.

In order to get the response code, all you have to do is:

cast the response as NSHTTPURLResponse then call the statusCode property

So your code would be:

let task = session.dataTaskWithRequest(request, completionHandler: {(data, response ,error ) in
        if let response = response {
            let httpResponse = response as! NSHTTPURLResponse
            print("response code = \(httpResponse.statusCode)")
        }
    })
task.resume()

You had an error which is calling the task.resume() inside the clouser, I fix it too.

Don't forget to check for errors as well

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM