1

当尝试通过 http 向服务器发送 post 数据时,它不返回任何 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()

结果是:

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

4

3 回答 3

0

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

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

request.httpBody = jsonData

于 2017-05-12T20:03:16.327 回答
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 个帖子变量....

于 2017-05-16T21:30:56.947 回答
0

我认为 http post/get request params = "param1=value¶m2=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()
        }
于 2017-05-26T13:24:33.130 回答