Swift http post没有帖子数据

时间:2017-05-12 18:57:10

标签: json swift http post urlsession

当尝试通过http将帖子数据发送到服务器时,它不会返回任何帖子数据。这是一个示例代码:

var request = URLRequest(url: URL(string: "http://posttestserver.com/post.php")!)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
let json = "{\"key\":\"c7cbdc09820372\",\"rand\": \"13baa5274c2b107727\"}"
request.httpBody = json.data(using: .utf8)
URLSession.shared.dataTask(with: request) { (data, response, error) in
      if data != nil, let result = String(data: data!, encoding: .utf8) {
          print("\(result)")
      }
}.resume()

结果是:

  

成功转储0个后变量...没有帖子正文。

3 个答案:

答案 0 :(得分:0)

将您的json字符串转换为字典然后

jsonData =试试? JSONSerialization.data(withJSONObject:dict,options:.prettyPrinted)

request.httpBody = jsonData

答案 1 :(得分:0)

如果有人需要,此代码可以使用:

var request = URLRequest(url: URL(string: "http://posttestserver.com/post.php")!)
request.httpMethod = "POST"
let data = "key=c7cbdc09820372&rand=13baa5274c2b107727"
request.httpBody = json.data(using: .utf8)
URLSession.shared.dataTask(with: request) { (data, response, error) in
    if data != nil, let result = String(data: data!, encoding: .utf8) {
        print("\(result)")
    }
}.resume()

给出:

  

成功转储了2个变量....

答案 2 :(得分:0)

我认为http post / get请求的最佳功能 params =“param1 = value& param2 = value2” 如果你想使用json,你应该改为Content-Type值,不要忘记

public func HttpPost(params:String, completion: @escaping (_ success: Bool, _ object: NSDictionary?) -> ()) {
            let configuration = URLSessionConfiguration.default
            let session = URLSession(configuration: configuration)
            let url = NSURL(string: /* here post url */)
            var request = URLRequest(url: url! as URL)
            request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
            request.httpMethod = "POST"
            request.httpBody = params.data(using: String.Encoding.utf8)!
            let task = session.dataTask(with: request) {
                data, response, error in
                if let httpResponse = response as? HTTPURLResponse {
                    let json = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments)
                    if json == nil {
                        completion(false, nil)
                    }
                    else{
                        completion(true, json as! NSDictionary?)
                    }
                }
                if (error != nil) {
                    completion(false, nil)
                }
            }
            task.resume()
        }