简体   繁体   中英

Media type is unsupported error in json post method Swift

I'm new to swift and making a simple application that converts Celsius to Fahrenheit using this : JSON WebService

My code is on a button btn action:

 @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()

 }

But it is giving me error like this on console:

pass 1
pass 2
pass 3
responseString =  Optional(The server cannot service the request because the media type is unsupported.)
Error 2

Plaese help thank u :)

1 - You should set your request Content-Type :

request.setValue(" application/json; charset=utf-8", forHeader:"Content-Type")

2 - Your body is not in JSON format, use :

let params = ["nCelscius" : 1212]
request.HTTPBody = NSJSONSerialization.dataWithJSONObject(params, options: NSJSONWritingOptions())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM