带有主体的HTTP Post请求返回null

时间:2018-07-24 13:09:16

标签: swift post httprequest nsurlrequest swifty-json

我正在尝试使用以下代码通过Swift URLRequest将一些数据发布到服务器。

var request = URLRequest(url: URL(string: Global.ip)!)
request.httpMethod = "POST"
request.addValue("application/x-www-form-urlencoded; charset=UTF-8", forHTTPHeaderField: "Content-Type")

let postString = "cmd=getFavorites" + "&ab={\"userId\":\"\(userId)\",\"favId\":\"\(favoriteId)\",\"favoriData\":\(panelData)}&token=\(token)"
let newPostString = postString.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)
request.httpBody = newPostString?.data(using: .utf8)

let task = URLSession.shared.dataTask(with: request)
{                                                   data, response, error in

    guard let data = data, error == nil else {
        print("error=\(String(describing: error))")
        completion(false)
        return;
    }
    let json = JSON(data)
    completion(true)
}
task.resume()

我的面板数据由许多json组成,如下所示。可能是十多个面板数据,例如JSON以下。

{"userId":"sampleUser","favoriId":"123456","favoriPanelData":[{"filterData": {
  "type" : "0",
  "code" : "0",
  "year" : 2018,
  "value1" : "0",
  "value2" : false,
  "value3" : "0",
  "value4" : "2018\/06",
  "value5" : 2018
},"defName":"abc","config": {
  "left" : 0,
  "height" : "6",
  "resizable" : true,
  "titlebar" : true,
  "settings" : true,
  "draggable" : true,
  "width" : 5,
  "bottom" : 6,
  "right" : 5,
  "top" : 0
},"memberName":"genName1"}]}

但是,它没有将该URL发布到服务器,并且我不明白为什么会发生。当我问我们的服务器端时,他们告诉我url有一个发布限制,很可能您没有发送POST请求。当我像上面在Swift中研究互联网POST请求时。我在哪里想念我该如何发送POST请求,这样才不会遇到限制?

0 个答案:

没有答案