简体   繁体   中英

Create POST request with JSON params

How to create a POST request as follows:

KEY = params

VALUE = {"api_key": "abc123"}

Eg. POST: params=value


let resourceURL = "https://127.0.0.1"
let apiKey:String = "abc123"

let params = ["api_key": apiKey] as Dictionary<String, String>
    do {
        let jsonParams = try JSONSerialization.data(withJSONObject: params, options: .sortedKeys)
    
    } catch {
        print("Error in JSON.")
    }

var request = URLRequest(url: URL(string: resourceURL)!)
let headers = ["Content-Type": "application/x-www-form-urlencoded"]
                
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers

Example request from postman:

在此处输入图像描述

To make x-www-form-urlencoded body try something like this:

var comps = URLComponents()
comps.queryItems = [URLQueryItem(name: "params", value: "{\"api_key\": \"abc123\"}")]
request.httpBody = comps.query?.data(using: .utf8)

You may check more details in this article

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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