为什么它给我代码:400和连接关闭?

时间:2016-06-09 03:34:31

标签: ios swift nsurlsession

回应:

  

可选({URL:myurllink} {状态代码:400,标题{连接=关闭;"内容 - 语言" = zh;"内容长度" = 1105;&# 34; Content-Type" =" text / html; charset = utf-8&#34 ;;

以下代码:

var request = NSMutableURLRequest(URL: NSURL(string: "http://www.myurl/")!)
var session = NSURLSession.sharedSession()
request.HTTPMethod = "POST"

var params1 = ["dailyspecial_name" : dailyspecial_name.text!,
              "dailyspecial_description" : dailyspecial_description.text!,
              "dailyspecial_type" :dailyspecial_type.text!]

var params = ["data" : params1,"label" : ""] as Dictionary<String, AnyObject>
var err: NSError?
request.HTTPBody = (try!NSJSONSerialization.dataWithJSONObject(params, options:  NSJSONWritingOptions()))
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")

var task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
    print("Response: \(response)")
    var strData = NSString(data: data!, encoding: NSUTF8StringEncoding)
    print("Body: \(strData)")
    var err: NSError?
    var json = (try!NSJSONSerialization.JSONObjectWithData(data!, options: .AllowFragments)) as? NSDictionary

    // Did the JSONObjectWithData constructor return an error? If so, log the error to the console
    if(err != nil) {
        print(err!.localizedDescription)
        let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)
        print("Error could not parse JSON: '\(jsonStr)'")
    }
    else {
        // The JSONObjectWithData constructor didn't return an error. But, we should still
        // check and make sure that json has a value using optional binding.
        if let parseJSON = json {
            // Okay, the parsedJSON is here, let's get the value for 'success' out of it
            var success = parseJSON["success"] as? Int
            print("Succes: \(success)")
        }
        else {
            // Woa, okay the json object was nil, something went worng. Maybe the server isn't running?
            let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)
            print("Error could not parse JSON: \(jsonStr)")
        }
    }
})

task.resume()

0 个答案:

没有答案