【问题标题】:HTTP Request with Body using PATCH in Swift在 Swift 中使用 PATCH 的 HTTP 请求
【发布时间】:2015-07-03 10:40:58
【问题描述】:

我正在尝试发送带有序列化 JSON 正文的 Patch 请求。

由于某种原因,服务器无法正确接收正文。感觉PATCH方法结合http请求体好像有问题。

    let sessionConfig = NSURLSessionConfiguration.defaultSessionConfiguration()
    let session = NSURLSession(configuration: sessionConfig, delegate: nil, delegateQueue: nil)

    var URL = B2MFetcher.urlForBooking(event.unique, bookingID: booking.unique)
    let request = NSMutableURLRequest(URL: URL)
    request.HTTPMethod = "PATCH"

    // Headers
    println(token)
    request.addValue(token, forHTTPHeaderField: "Authorization")
    request.addValue("gzip, identity", forHTTPHeaderField: "Accept-Encoding")

    // JSON Body
    let bodyObject = [
        "op": "cancel"
    ]
    var jsonError: NSError?
    request.HTTPBody = NSJSONSerialization.dataWithJSONObject(bodyObject, options: nil, error: &jsonError)

    /* Start a new Task */
    let task = session.dataTaskWithRequest(request, completionHandler: { (data : NSData!, response : NSURLResponse!, error : NSError!) -> Void in
        completion(data: data, response:response , error: error)
    })
    task.resume()

【问题讨论】:

    标签: ios swift rest http patch


    【解决方案1】:

    您可以尝试在请求中添加 Content-Type 标头:

    request.addValue("application/json", forHTTPHeaderField: "Content-Type")
    

    或使用here 所述的其他 JSON Content-Type 格式之一。

    我使用 ExpressJS 服务器对其进行了测试,没有 Content-Type 标头,服务器得到一个空的主体,但使用 Content-Type 标头它运行良好。

    【讨论】:

      【解决方案2】:

      在 Swift 3/4 中:

       let request = NSMutableURLRequest(url: NSURL(string: "http://XXX/xx/xxx/xx")! as URL)
              request.httpMethod = "PATCH"
              request.addValue("application/json", forHTTPHeaderField: "Content-Type")
              do{
      
                 let json: [String: Any] = ["status": "test"]
                 let jsonData = try? JSONSerialization.data(withJSONObject: json)
                  request.httpBody = jsonData
                  print("jsonData: ", String(data: request.httpBody!, encoding: .utf8) ?? "no body data")
              } catch {
                  print("ERROR")
              }
      
              let task = URLSession.shared.dataTask(with: request as URLRequest) {
                  data, response, error in
      
                  if error != nil {
                      print("error=\(error)")
                      completion(false)
                      return
                  }
      
                  let responseString = NSString(data: data!, encoding:            String.Encoding.utf8.rawValue)
                  print("responseString = \(responseString)")
                  completion(true)
                  return
              }
              task.resume()
      

      【讨论】:

        【解决方案3】:

        不使用HTTPBody的简单方法使用补丁

        如果你只想使用补丁,你只需要改变一个特定用户的名字的值,那么它将是这样的:

        let myurl = URL(string: "https://gorest.co.in/public-api/users/"+"\(id)?"+"name=abc")!
        
        var request = URLRequest(url:myurl)
        request.addValue("Bearer yourAuthorizationToken",forHTTPHeaderField:"Authorization")
        request.httpMethod = "PATCH"
        
        let dataTask = URLSession.shared.dataTask(with: request)
        dataTask.resume()
        

        注意:这里的"id" 将是userId

        【讨论】:

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