请求后请求状态码400错误

时间:2021-07-06 18:33:29

Why after all the below code, after I do a po NSKeyedUnarchiver.unarchiveObject(with: (response.request?.httpBody)!) I get nil ? And the response code is 400. And the reason the response code is 400, I believe is because of the parameters. Any suggestions why this happens?

为什么在完成以下代码之后,我做了一个po NSKeyedUnarchiver.unarchiveObject(带:(response.request?.httpBody)!)我得到了什么?并且响应代码是400.响应代码为400的原因,我相信是因为参数。有什么建议为什么会这样?

let urlRequest = NSMutableURLRequest(url: url)
let bodyData = parameters.first!.key + "=" + String(describing: parameters.first!.value)

urlRequest.bind(to: command!)
urlRequest.httpBody = bodyData.data(using: .utf8)
urlRequest.httpMethod = "POST"
urlRequest.allHTTPHeaderFields = NetworkManager.defaultHeaders()

return Alamofire.request(urlRequest.copy() as! URLRequest)

EDIT: Ok, so I replaced some lines and now the code looks like this and the parameters are no longer nil:

编辑:好的,所以我替换了一些行,现在代码看起来像这样,参数不再是零:

let urlRequest = NSMutableURLRequest(url: url)
let dataParameters: Data = NSKeyedArchiver.archivedData(withRootObject: parameters)

urlRequest.bind(to: command!)
urlRequest.httpBody = dataParameters
urlRequest.httpMethod = HTTPMethod.post.rawValue
urlRequest.allHTTPHeaderFields = NetworkManager.defaultHeaders()

return Alamofire.request(urlRequest.copy() as! URLRequest)

But even like this I get a 400 code. So after investigating a little with postman I found that if I put the body like this {"xxxxx":"xxxxxxxxx"} it works and I get a good code, but if I use a key and value it doesn't. How do I make that work?

但即使这样我也得到400代码。所以在对邮递员进行了一些调查之后,我发现如果我把这个身体放在这个{“xxxxx”:“xxxxxxxxx”}它可以工作,我得到了一个很好的代码,但是如果我使用一个密钥和值,它就不会。我该如何工作?

1 个解决方案

#1


0  

So I found why I got the bad request and the answer was really simple. Just had to use json serialization.

所以我找到了为什么我得到了错误的请求,答案非常简单。只是不得不使用json序列化。

And I just replaced this

而我刚刚取代了这个

let jsonData = try? JSONSerialization.data(withJSONObject: parameters)
urlRequest.httpBody = jsonData

with this

let dataParameters: Data = NSKeyedArchiver.archivedData(withRootObject: parameters)
urlRequest.httpBody = dataParameters

I'll just leave this here in case someone has the same problem as me.

我会把这个放在这里以防有人和我有同样的问题。

#1


0  

So I found why I got the bad request and the answer was really simple. Just had to use json serialization.

所以我找到了为什么我得到了错误的请求,答案非常简单。只是不得不使用json序列化。

And I just replaced this

而我刚刚取代了这个

let jsonData = try? JSONSerialization.data(withJSONObject: parameters)
urlRequest.httpBody = jsonData

with this

let dataParameters: Data = NSKeyedArchiver.archivedData(withRootObject: parameters)
urlRequest.httpBody = dataParameters

I'll just leave this here in case someone has the same problem as me.

我会把这个放在这里以防有人和我有同样的问题。