如何在 Swift 5 中发送带有 httpBody 表单数据的 POST 请求?
How to send POST request with httpBody form-data in Swift 5?
I want to send POST request in form like this
我尝试了下面的代码。但是,我没有成功。
let url = URL(string: "https://www.blablabla.com")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
let json: [String: Any] = ["test":"info"]
let jsonData = try? JSONSerialization.data(withJSONObject: json)
if let JSONString = String(data: jsonData!, encoding: String.Encoding.utf8) {
let req = "{TestRequest=" + JSONString + "}"
// Also, I tried this: let req = "TestRequest=" + JSONString
request.httpBody = req.data(using: String.Encoding.utf8)
}
URLSession.shared.dataTask(with: url) {(data, response, error) in
do {
// JSON Parsing
} catch {
// Show error message
}
}.resume()
我遇到了这个错误:
dataCorrupted(Swift.DecodingError.Context(codingPath: [], debugDescription: "The given data was not valid JSON.", underlyingError: Optional(Error Domain=NSCocoaErrorDomain Code=3840 "No value." UserInfo={NSDebugDescription=No value.})))
当我尝试使用 Postman 时,它运行流畅。
对不起,我写错了代码。当我尝试下面的代码时,我成功了。
let url = URL(string: "https://www.blablabla.com")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
let req = "TestRequest={\"test\":\"info\"}"
request.httpBody = req.data(using: String.Encoding.utf8)
URLSession.shared.dataTask(with: request) {(data, response, error) in
do {
// JSON Parsing
} catch {
// Show error message
}
}.resume()
主要问题是使用 "url" 而不是 "request" 开始会话。
I want to send POST request in form like this
我尝试了下面的代码。但是,我没有成功。
let url = URL(string: "https://www.blablabla.com")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
let json: [String: Any] = ["test":"info"]
let jsonData = try? JSONSerialization.data(withJSONObject: json)
if let JSONString = String(data: jsonData!, encoding: String.Encoding.utf8) {
let req = "{TestRequest=" + JSONString + "}"
// Also, I tried this: let req = "TestRequest=" + JSONString
request.httpBody = req.data(using: String.Encoding.utf8)
}
URLSession.shared.dataTask(with: url) {(data, response, error) in
do {
// JSON Parsing
} catch {
// Show error message
}
}.resume()
我遇到了这个错误:
dataCorrupted(Swift.DecodingError.Context(codingPath: [], debugDescription: "The given data was not valid JSON.", underlyingError: Optional(Error Domain=NSCocoaErrorDomain Code=3840 "No value." UserInfo={NSDebugDescription=No value.})))
当我尝试使用 Postman 时,它运行流畅。
对不起,我写错了代码。当我尝试下面的代码时,我成功了。
let url = URL(string: "https://www.blablabla.com")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
let req = "TestRequest={\"test\":\"info\"}"
request.httpBody = req.data(using: String.Encoding.utf8)
URLSession.shared.dataTask(with: request) {(data, response, error) in
do {
// JSON Parsing
} catch {
// Show error message
}
}.resume()
主要问题是使用 "url" 而不是 "request" 开始会话。