花了很多时间没有成功。 我正在使用Alamofire对后端服务器进行HTTP POST,这需要一些参数来提供请求。 我成功点击了服务器,但是服务器响应500表示没有发送参数?
我已尝试过大多数SO解决方案(更改编码类型,将参数设置为NSDict等),但没有成功。
非常感谢任何帮助。
PS其Swift3与Alamofire 4
代码:
let params: [String: String] = ["deviceID": "Some device ID",
"email": "email","password": "password","userid": "1234",
"username":"gordon"]
let request_params: Parameters = ["LoginUser" : params]
let url = "https://myserver/LogIn" as String
Alamofire.request(url, method: .post, parameters: request_params, encoding: URLEncoding.default, headers: [
"Content-Type": "application/x-www-form-urlencoded"
]).responseString { (response:DataResponse<String>) in
switch(response.result) {
case.success(let data):
print("success",data)
print(response.response)
case.failure(let error):
print("Failed!",error)
}
}
更新
以下是POST的正文,看起来这就是问题所在:
Alamofire POST正文(来自上面的代码) - (LoginUser%5BdeviceID%5D = 12345&安培; LoginUser%5Bemail%5D =戈登%40test.com&安培; LoginUser%5Buserid%5D = 00000000-0000-0000-0000-000000000000&安培; LoginUser%5Bpassword%5D = testPassword&安培; LoginUser%5Busername%5D =戈登)
应该是(忽略编码值):
这是一个功能性帖子 - LoginUser =%7B%22deviceID%22%3A%22%22%2C%22email%22%3A%22gordon%40test.com%22%2C%22password%22%3A%22testPassword%22%2C%22userid%22%3A %2200000000-0000-0000-0000-000000000000%22%2C%22username%22%3A%22gordon%22%7D
正如您所看到的,Alamofire帖子似乎将LoginUser连接到每个属性的开头?还缺少LoginUser = at ?? ??
答案 0 :(得分:1)
尝试使用JSONEncoding.default
代替URLEncoding.default
答案 1 :(得分:0)
好的,所以我使用下面的代码工作,会非常有兴趣了解这是否是发布参数的最有效方法?
let params: NSMutableDictionary? = ["deviceID": "someDeviceID",
"email": "emailAddress","password": "aSecret","userid": "12345",
"username":"gordon"]
let url = "https://serverAdrress" as String
let data = try! JSONSerialization.data(withJSONObject: params!, options: JSONSerialization.WritingOptions.prettyPrinted)
let json: NSString! = NSString(data: data, encoding: String.Encoding.utf8.rawValue)
let request_params: Parameters = ["LoginUser" : json as Any]
Alamofire.request(url, method: .post, parameters: request_params, encoding: URLEncoding.httpBody, headers: [
"Content-Type": "application/x-www-form-urlencoded"
]).responseString { (response:DataResponse<String>) in
switch(response.result) {
case.success(let data):
print("success",data)
print(NSString(data: (response.request?.httpBody)!, encoding: String.Encoding.utf8.rawValue))
print(response.response)
case.failure(let error):
print("Not Success",error)
}
}