简体   繁体   English

如何使用swift作为邮递员请求测试对第http正文的行发出请求?

[英]how to make post request with row http body using swift as postman request test?

request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")

let httpbody = object.data(using: String.Encoding.utf8)
request.httpBody = httpbody

You can directly generate a code from postman itself. 您可以直接从邮递员本身生成代码。 Also, for your reference, you can call post request with row body as given below. 另外,作为参考,您可以使用下面给出的行主体来调用发布请求。

let headers = [
        "content-type": "application/json",
        "cache-control": "no-cache"
    ]

    let parameters = ["order": ["line_items": [
                                            ["variant_id": 18055889387589,
                                             "quantity": 1]
                     ]]] as [String : Any]

    let postData = try? JSONSerialization.data(withJSONObject: parameters, options: [])

    if let data = postData {
        let request = NSMutableURLRequest(url: NSURL(string: "http://")! as URL,
                                          cachePolicy: .useProtocolCachePolicy,
                                          timeoutInterval: 10.0)
        request.httpMethod = "POST"
        request.allHTTPHeaderFields = headers
        request.httpBody = data as Data

        let session = URLSession.shared
        let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
            if (error != nil) {
                print(error?.localizedDescription ?? "")
            } else {
                let httpResponse = response as? HTTPURLResponse
                print(httpResponse?.statusCode ?? 0)


                let reponseData = String(data: data!, encoding: String.Encoding.utf8)
                print("responseData: \(reponseData ?? "Blank Data")")
            }
        })

        dataTask.resume()
    }

Let me know if you have any query. 让我知道您是否有任何疑问。

Thanks. 谢谢。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM