如何使用swift作为邮递员请求测试使用行http正文发出post请求? [英] how to make post request with row http body using swift as postman request test?

查看:40
本文介绍了如何使用swift作为邮递员请求测试使用行http正文发出post请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

推荐答案

您可以直接从邮递员本身生成代码.此外,为了您的参考,您可以使用如下所示的行正文调用 post 请求.

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.

谢谢.

这篇关于如何使用swift作为邮递员请求测试使用行http正文发出post请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆