【发布时间】:2018-06-29 11:16:03
【问题描述】:
我必须进行 API 调用,其中标头为“application/x-www-form-urlencoded”,正文中的“数据”为键,vakue 为 JSON 字符串。我必须以 application/x-www-form-urlencoded 格式传递数据。我附上了邮递员的截图,它工作正常。
[带有标头的图像][带有帖子数据的图像作为 x-www-form-urlencoded 标记]
我尝试了很多链接,例如POST request using application/x-www-form-urlencoded。但是找不到正确的。
我可以使用 Alamofire 等其他框架来解决这个问题。
我为此使用以下代码。
let url = URL(string: "http://mylocalhost/get-user-details")!
var request = URLRequest(url: url)
let jsonString = ["email":"example@domain.com"]
let postData = ["data":jsonString]
let jsonData = try! JSONSerialization.data(withJSONObject: postData, options: .prettyPrinted)
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.httpMethod = "POST"
request.httpBody = jsonData
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else { // check for fundamental networking error
print("error=\(error)")
return
}
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 { // check for http errors
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(response)")
}
let responseString = String(data: data, encoding: .utf8)
print("responseString = \(responseString)")
}
task.resume()
【问题讨论】:
-
JSONSerialization.data(withJSONObject: postData, options: .prettyPrinted)。不要使用prettyPrinted,这会添加无用的换行符。请改用JSONSerialization.data(withJSONObject: postData, options: [])。另外,我想知道您是否在 JSON 中没有婴儿 JSON。意思是jsonString必须是"{\"email\":\"example@domain.com\"},因为很明显,当它是字典时,将变量命名为jsonString,这是一种误导,但邮递员可以这么说。 -
为什么不简单地在“Content-Type”中使用“application/json”。