How to POST JSON data using NSURLSession in swift

蓝咒 提交于 2020-01-23 23:10:22

问题


I am stuck with the below code. How do I set the param and in post method?

let params:[String:Any] = [
        "email" : usr,
        "userPwd" : pwdCode]

let url = NSURL(string:"http://inspect.dev.cbre.eu/SyncServices/api/jobmanagement/PlusContactAuthentication")
let request = NSMutableURLRequest(URL: url!)
request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")

request.HTTPBody = params<what should do for Json parameter>


let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
    data, response, error in

    if let httpResponse = response as? NSHTTPURLResponse {
        if httpResponse.statusCode != 200 {
            println("response was not 200: \(response)")
            return
        }
    }
    if error {
        println("error submitting request: \(error)")
        return
    }

    // handle the data of the successful response here
}
task.resume()

回答1:


if I understand the question correctly

var configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
var session = NSURLSession(configuration: configuration)
var usr = "dsdd"
var pwdCode = "dsds"
let params:[String: AnyObject] = [
    "email" : usr,
    "userPwd" : pwdCode ]

let url = NSURL(string:"http://localhost:8300")
let request = NSMutableURLRequest(URL: url!)
request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
request.HTTPMethod = "POST"
var err: NSError?
request.HTTPBody = NSJSONSerialization.dataWithJSONObject(params, options: NSJSONWritingOptions.allZeros, error: &err)

let task = session.dataTaskWithRequest(request) {
    data, response, error in

    if let httpResponse = response as? NSHTTPURLResponse {
        if httpResponse.statusCode != 200 {
            println("response was not 200: \(response)")
            return
        }
    }
    if (error != nil) {
        println("error submitting request: \(error)")
        return
    }

    // handle the data of the successful response here
    var result = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.allZeros, error: nil) as? NSDictionary
    println(result)
}
task.resume()

I would suggest using AFNetworking. See for example, Posting JSON data using AFNetworking 2.0.




回答2:


This is how you can set parameters and send a POST request, easy approach using Alamofire.

  • Swift 2.2

    let URL = NSURL(string: "https://SOME_URL/web.send.json")!
    let mutableURLRequest = NSMutableURLRequest(URL: URL)
    mutableURLRequest.HTTPMethod = "POST"
    
    let parameters = ["api_key": "______", "email_details": ["fromname": "______", "subject": "this is test email subject", "from": "support@apple.com", "content": "<p> hi, this is a test email sent via Pepipost JSON API.</p>"], "recipients": ["_________"]]
    
    do {
        mutableURLRequest.HTTPBody = try NSJSONSerialization.dataWithJSONObject(parameters, options: NSJSONWritingOptions())
    } catch {
        // No-op
    }
    
    mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
    
    Alamofire.request(mutableURLRequest)
        .responseJSON { response in
            print(response.request)  // original URL request
            print(response.response) // URL response
            print(response.data)     // server data
            print(response.result)   // result of response serialization
    
            if let JSON = response.result.value {
                print("JSON: \(JSON)")
            }
    }
    


来源:https://stackoverflow.com/questions/27036233/how-to-post-json-data-using-nsurlsession-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!