我想将手机号码和密码发送到ios应用中的服务器。后端团队给出了邮政编码API,如下图所示。
以表单数据形式发送时成功
Swift网址请求失败,我在这里做错了什么?
func sendReq() {
let Url = String(format: "http://xxxxxxx/mobile/request_otp")
guard let serviceUrl = URL(string: Url) else { return }
let parameterDictionary = ["mobile_number" : "xxxxxxxxxx", "password" : "12345678"]
var request = URLRequest(url: serviceUrl)
request.httpMethod = "POST"
request.cachePolicy = .useProtocolCachePolicy
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
// params dict as data
guard let httpBody = try? JSONSerialization.data(withJSONObject: parameterDictionary, options: []) else {
return
}
request.httpBody = httpBody
// session
let session = URLSession.shared
//data task
session.dataTask(with: request) { (data, response, error) in
if let response = response {
print(response)
}
if let data = data {
do {
let json = try JSONSerialization.jsonObject(with: data, options: [])
print(json)
}
catch {
print(error)
}
}
}.resume()
}
但是上面的API调用抛出错误,如
{
error = TRUE;
message = "All fields Required!";
}
答案 0 :(得分:0)
你可以尝试:
{\"mobile_number\":xxxxxxxxxx,\"password\":12345678}
并选择Application / Json而不是text。
答案 1 :(得分:0)
设置Content-Type
HTTP标头:
request.allHTTPHeaderFields = ["Content-Type": "application/json"]
这样您就可以通知服务器您正在发送JSON。