首页 > 解决方案 > 如何在 swift 中在 POST 请求参数中发送字符串键和 json 值?

问题描述

我想在 POST 中发送一个请求参数,其中键是字符串格式,值是 json 格式,如下所示:

request parameter :     data={"firstName":"Pooja"}

请在 swift 4.1 中找到以下代码片段

 let myUrl = URL(string: chatService)
        print(myUrl)
        var request = URLRequest(url:myUrl!)
        request.httpMethod = "POST"// Set POST method
        request.addValue("Content-Type", forHTTPHeaderField: "application/x-www-form-urlencoded")
        let postString = 'data={"firstName":"Pooja"}'
        request.httpBody = postString.data(using: String.Encoding.utf8);

        let task = defaultSession.dataTask(with: request) { (data: Data?, response: URLResponse?, error: Error?) in

标签: iosswift

解决方案


let url = URL(string: "http://www.thisismylink.com/postName.php")!
var request = URLRequest(url: url)
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField:"Content-Type")
request.httpMethod = "POST"
let postString = "id=13&name=Jack"
request.httpBody = postString.data(using: .utf8)
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else {                                                 // check for fundamental networking error
    print("error=\(error)")
    return
}

if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {           // check for http errors
    print("statusCode should be 200, but is \(httpStatus.statusCode)")
    print("response = \(response)")
}

let responseString = String(data: data, encoding: .utf8)
print("responseString = \(responseString)")}task.resume()}

使用上面的代码


推荐阅读