我是swift的新手,并制作了一个简单的应用程序,使用它将Celsius转换为Fahrenheit:JSON WebService
我的代码位于按钮btn
上:
@IBAction func btn(sender: AnyObject) {
let celnum = txtfirld.text
let myUrl = NSURL(string: "http://webservices.daehosting.com/services/TemperatureConversions.wso");
print("pass 1")
let request = NSMutableURLRequest(URL: myUrl!);
request.HTTPMethod = "POST";
print("pass 2")
let postString = "nCelsius=\(celnum)"
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding);
let task = NSURLSession.sharedSession().dataTaskWithRequest(request){
data, response, error in
print("pass 3")
if error != nil {
print("Error 1")
return
}
let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("responseString = \(responseString)")
do{
let json = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableLeaves) as? NSDictionary
if let parseJson = json{
let resultValue = parseJson["status"] as! String!
print("result:\(resultValue)")
}
} catch {print("Error 2")}
}
task.resume()
}
但它在控制台上给我这样的错误:
pass 1
pass 2
pass 3
responseString = Optional(The server cannot service the request because the media type is unsupported.)
Error 2
Plaese帮助谢谢你:)
答案 0 :(得分:1)
1 - 您应该设置您的请求Content-Type:
request.setValue(" application/json; charset=utf-8", forHeader:"Content-Type")
2 - 您的身体不是JSON格式,请使用:
let params = ["nCelscius" : 1212]
request.HTTPBody = NSJSONSerialization.dataWithJSONObject(params, options: NSJSONWritingOptions())