如何在POST请求参数中快速发送字符串键和json值?

时间:2018-12-07 12:46:11

标签: ios swift

我想在POST中发送一个请求参数,其中的Key是String格式,值是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

2 个答案:

答案 0 :(得分:0)

您不应尝试将JSON内容放入查询参数中。会造成问题。如果您需要在POST中包含JSON,则应在正文中,而不是URL中。

由于多种原因,您尝试执行的操作无法正常运行。有多种字符在JSON中合法,但在查询参数中不合法,并且查询参数的长度非常有限。

答案 1 :(得分:0)

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()}

使用上面的代码