Swift http post 没有 post 数据

Swift http post has no post data

当尝试通过 http 向服务器发送 post 数据时,return 没有 post 数据。这是一个示例代码:

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

结果是:

Successfully dumped 0 post variables... No Post body.

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

json数据=试试? JSONSerialization.data(withJSONObject: dict, options: .prettyPrinted)

request.httpBody = json数据

此代码有效,以防万一有人需要:

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

给出:

Successfully dumped 2 post variables....

我认为 http post/get 请求的最佳功能 参数 = "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()
        }