json Swift http post没有post数据

q0qdq0h2  于 2023-05-19  发布在  Swift
关注(0)|答案(3)|浏览(140)

当尝试通过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个发布变量...无柱体。

syqv5f0l

syqv5f0l1#

这段代码可以工作,如果有人需要:

var request = URLRequest(url: URL(string: "http://posttestserver.com/post.php")!)
request.httpMethod = "POST"
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()

提供:
已成功转储2个post变量....

nkoocmlb

nkoocmlb2#

将你的json字符串转换成字典,然后
jsonData = try?JSONSerialization.data(withJSONObject:dict,选项:.prettyPrinted)
request.httpBody = jsonData

c9x0cxw0

c9x0cxw03#

我认为最好的函数为http post/get request params =“param 1 =value&param2= value 2”如果你想使用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()
        }

相关问题