【问题标题】:How to send string key and json value in POST request parameter in swift?如何在 swift 中在 POST 请求参数中发送字符串键和 json 值?
【发布时间】:2018-12-08 00:03:41
【问题描述】:

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

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

请在 swift 4.1 中找到下面的代码 sn-p

 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

【问题讨论】:

标签: ios swift


【解决方案1】:

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

由于多种原因,您尝试执行的操作无法正常工作。有各种字符在 JSON 中是合法的,但在查询参数中是不合法的,而且你的查询参数的长度是相当有限的。

【讨论】:

    【解决方案2】:
    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()}
    

    使用上面的代码

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-04
      • 1970-01-01
      • 1970-01-01
      • 2016-03-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多