[英]swift - how to get JSON response from server
I'm sending this data to a server and I would like it to respond. 我正在将此数据发送到服务器,我希望它能够响应。 Tried this code but it doesn't work. 尝试过此代码,但不起作用。
let parameters = [ "imie" : (imie), "nazwisko" : (nazwisko), "telefon" : (telefon), "adres" : (adres), "miasto" : (miasto), "kod" : (kod), /*"powiat" : (powiat), "wojewodztwo" : (wojewodztwo),*/ "opis" : (selectedvalue) ]
let url = URL(string: "http://www.hetman.pl/post1.php")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Accept")
request.setValue("application/x-www-form-urlencoded; charset=utf-8", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.setBodyContent(parameters)
let task = URLSession.shared.dataTask(with: request as URLRequest) { data, response, error in
if error != nil{
return
}
do{
let t = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String:AnyObject]
print(t as? String)
} catch{
print("Error 43 -> \(error)")
}
}
Request is correct and server is processing data properly, but response gives me this error: 请求正确,服务器正在正确处理数据,但是响应给了我这个错误:
Error 43 -> Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 3." UserInfo={NSDebugDescription=Invalid value around character 3.}
So the question is, how do I get the data back from server? 所以问题是,如何从服务器取回数据?
Why there is to content type? 为什么要内容类型?
// code 3840, data.length = 1 byte, so empty and no error
request.setValue("application/x-www-form-urlencoded; charset=utf-8", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
Remove first content-type header field and try with only: 删除第一个内容类型标头字段,然后仅尝试:
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
Please check if response from this url is JSON only. 请检查此网址的响应是否仅为JSON。 You might be getting XML or string response. 您可能正在获取XML或字符串响应。
Try below line if you are getting String response : 如果您得到String响应,请尝试以下行:
let stringResponse = String(data: data!, encoding: String.Encoding.utf8) as String!
Try below line if you are getting XML response : 如果您收到XML响应,请尝试以下行:
let xmlDictionary = try XMLSerialization.xmlObject(with: data!) as? [String: Any]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.