簡體   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

您可以直接從郵遞員本身生成代碼。 另外,作為參考,您可以使用下面給出的行主體來調用發布請求。

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

讓我知道您是否有任何疑問。

謝謝。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM