简体   繁体   English

NSURLSession从Servlet获取响应

[英]NSURLSession get response from Servlet

Currently, I am using NSURLSession and HTTPPost method to upload data to Java servlet. 当前,我正在使用NSURLSession和HTTPPost方法将数据上传到Java servlet。 The java servlet will parse the data received and update it into database. Java Servlet将解析接收到的数据并将其更新到数据库中。

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. 在更新过程中(在Java中),将根据不同的条件将不同的状态标志更新到DB中。 Now, my requirement is to get that status returned from the web server and show locally. 现在,我的要求是从Web服务器获取该状态并在本地显示。

I am aware that I can use HTTPGet method again, pass the key value and get the status flag. 我知道我可以再次使用HTTPGet方法,传递键值并获取状态标志。

I am trying to explore if there are any callback handlers available to use with java servlets like the one available in javascript. 我正在尝试探索是否有任何可与Java servlet一起使用的回调处理程序,如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 将响应转换为NSHTTPURLResponse然后调用statusCode属性

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. 您在task.resume()内调用task.resume()遇到了错误,我也对此进行了修复。

Don't forget to check for errors as well 别忘了检查错误

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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