如何使用不同的对象发出此POST请求?
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何使用不同的对象发出此POST请求?相关的知识,希望对你有一定的参考价值。
Overview:
我正在尝试发出一个POST请求,我之前只使用字符串。这一次,我有一些变量,分别是:String
,Int
和Bool
。
Error:
Cannot assign value of type [String : Any] to type Data
Line causing the error:
request.httpBody = paramToSend
Question:
- 如何将
Dictionary
转换成Data
?
Complete Code:
func sendComplimentAPI (message: String, recipient: Int, isPublic: Bool) {
let url = URL(string: "https://complimentsapi.herokuapp.com/compliments/send/")
let session = URLSession.shared
let preferences = UserDefaults.standard
let request = NSMutableURLRequest(url: url!)
request.addValue("(preferences.object(forKey: "token") as! String)", forHTTPHeaderField: "Authorization")
request.httpMethod = "POST"
let paramToSend = ["message":message,"recipient":recipient,"is_public":isPublic] as [String : Any]
request.httpBody = paramToSend
let task = session.dataTask(with: request as URLRequest, completionHandler: {
(data, response, error) in
guard let _:Data = data else {return}
let json:Any?
do{json = try JSONSerialization.jsonObject(with: data!, options: [])}
catch {return}
guard let server_response = json as? NSDictionary else {return}
if let session_data = server_response["id"] as? String {
print("worked")
//do something
/*DispatchQueue.main.async (
execute:
)*/
} else {
print("error")
}
})
task.resume()
}
编辑:
我尝试过这个新代码,但仍未发布到服务器上。我附加了我改变的内容,并且还编写了控制台为我所做的两个打印件显示的内容。
let paramToSend = ["message":writeTextField.text!,"recipient":1,"is_public":isPrivate] as [String : Any] //messageString + recipientString + isPublicString
do {
var serialized = try JSONSerialization.data(withJSONObject: paramToSend, options: .prettyPrinted)
print(serialized)
request.httpBody = serialized
print(request.httpBody)
} catch {
print("found a problem")
}
控制台返回(对于序列化,然后是HTTP正文):113字节可选(113字节)
这是可选的导致问题吗?我如何解决它?
答案
要将Dictionary
转换为Data
,请使用JSONSerialization.data
:
Solution:
JSONSerialization.data(withJSONObject: paramToSend, options: .prettyPrinted)
Check the request:
- 打印请求,看看它是否符合您的期望
Reading the response:
//Check if there is any error (check if error != nil)
//Examine the response
let statusCode = (response as? HTTPURLResponse)?.statusCode
let statusCodeDescription = (response as? HTTPURLResponse)?.localizedString(forStatusCode: httpResponse.statusCode)
//Check Data
if let data = data {
let dataString = String(data: data, encoding: String.Encoding.utf8)
}
另一答案
事实证明我需要添加一个简单的附加标题来使整个过程发挥作用。
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
这可能是为什么它不理解我发送它的字典
以上是关于如何使用不同的对象发出此POST请求?的主要内容,如果未能解决你的问题,请参考以下文章
如何使用自定义 React 钩子通过 Axios 发出 POST 或 DELETE 请求