How to make HTTP Post request with JSON body in Swift

Try this,

// prepare json data
let json: [String: Any] = ["title": "ABC",
                           "dict": ["1":"First", "2":"Second"]]

let jsonData = try? JSONSerialization.data(withJSONObject: json)

// create post request
let url = URL(string: "http://httpbin.org/post")!
var request = URLRequest(url: url)
request.httpMethod = "POST"

// insert json data to the request
request.httpBody = jsonData

let task = URLSession.shared.dataTask(with: request) { data, response, error in
    guard let data = data, error == nil else {
        print(error?.localizedDescription ?? "No data")
        return
    }
    let responseJSON = try? JSONSerialization.jsonObject(with: data, options: [])
    if let responseJSON = responseJSON as? [String: Any] {
        print(responseJSON)
    }
}

task.resume()

如果遇到有問題,這段 code 可以派上用場:

               if let stringData = String(data: data, encoding: String.Encoding.utf8) {
                    print(stringData)
               }

把 binary 轉 string

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *