我想在下面的代码中设置内容类型来调用web api。
内容类型为application/json; charset=utf-8
let url = NSURL(string: "http:/api/jobmanagement/PlusContactAuthentication?email=\(usr)&userPwd=\(pwdCode)")
println("URL: \(url)")
let task = NSURLSession.sharedSession().dataTaskWithURL(url!) {
(data, response, error) in
println(NSString(data: data, encoding: NSUTF8StringEncoding))
}
// task.setValue(<#value: AnyObject?#>, forKey: <#String#>)
task.resume()
答案 0 :(得分:41)
如果您要设置请求的Content-Type
,可以创建自己的NSMutableURLRequest
,提供您的网址,使用Content-Type
指定setValue:forHTTPHeaderField:
标题,然后发出使用dataTaskWithRequest
而不是dataTaskWithURL
的请求。因此,在Swift 2中,您可以将request.HTTPBody
设置为JSON并指定它是POST请求:
let request = NSMutableURLRequest(URL: url!)
request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type") // the request is JSON
request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Accept") // the expected response is also JSON
request.HTTPMethod = "POST"
request.updateBasicAuthForUser("test", password: "password1")
let dictionary = ["email": usr, "userPwd": pwdCode]
request.HTTPBody = try! NSJSONSerialization.dataWithJSONObject(dictionary, options: [])
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { data, response, error in
guard let data = data where error == nil else {
print(error) // some fundamental network error
return
}
do {
let responseObject = try NSJSONSerialization.JSONObjectWithData(data, options: [])
print(responseObject)
} catch let jsonError {
print(jsonError)
print(String(data: data, encoding: NSUTF8StringEncoding)) // often the `data` contains informative description of the nature of the error, so let's look at that, too
}
}
task.resume()
在Swift 3中,等效代码为:
var request = URLRequest(url: url!)
request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type") // the request is JSON
request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Accept") // the expected response is also JSON
request.httpMethod = "POST"
let dictionary = ["email": usr, "userPwd": pwdCode]
request.httpBody = try! JSONSerialization.data(withJSONObject: dictionary)
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else {
print(error) // some fundamental network error
return
}
do {
let responseObject = try JSONSerialization.jsonObject(with: data)
print(responseObject)
} catch let jsonError {
print(jsonError)
print(String(data: data, encoding: .utf8)) // often the `data` contains informative description of the nature of the error, so let's look at that, too
}
}
task.resume()
答案 1 :(得分:0)
这对于我使用SWIFT 5进行API调用开发iOS应用程序非常有用。没有这两行,GET方法就可以正常工作。 PUT和POST方法会将值发送到API服务器,但是一旦到达服务器,它就无法解释JSON数据,因此我的数据库将为所有字段插入NULL值。添加这两行后,数据已正确传输到表中。希望这可以节省其他人的时间。
request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Accept")