简体   繁体   中英

HTTP Post Request in Swift Crashing

For some reason, my code is breaking every time I attempt to make a POST request.

My code is:

let request = NSMutableURLRequest(URL: NSURL(string: "https://url.info/")!);
    request.HTTPMethod = "POST";
    let postString = "?appendedToURL";
    request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding);
    let task = NSURLSession.sharedSession().dataTaskWithRequest(request){
        data, response, error in
        if error != nil{
            println("error=\(error)");
            return;
        }
        println("response = \(response)");
        let responseString = NSString(data: data, encoding: NSUTF8StringEncoding);
        println("responseString = \(responseString)");
    }
    task.resume();

I keep being sent to the debugger from the line:
let task = NSURLSession.sharedSession().dataTaskWithRequest(request)

I'm not really sure what I'm doing wrong here, any help would be appreciated.

I tried to get the above requests, but could not get any response. (I used https://www.getpostman.com/ )

If you want to get a response, I recommend you use https://httpbin.org/ .

This is the example that works.

let request = NSMutableURLRequest(URL: NSURL(string: "http://httpbin.org/post")!)
request.HTTPMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")

let params: [String: AnyObject] = [
    "foo": "bar",
    "baz": [
        "a": 1,
        "b": 20,
        "c": 300
    ]
]
request.HTTPBody = NSJSONSerialization.dataWithJSONObject(params, options: nil, error: nil)

let task = NSURLSession.sharedSession().dataTaskWithRequest(request){ data, response, error in
    if error != nil{
        println("error=\(error)")
        return
    }
    println("response = \(response)")
    let responseString = NSString(data: data, encoding: NSUTF8StringEncoding)
    println("responseString = \(responseString)")
}

task.resume()

The output is like this,

response = <NSHTTPURLResponse: 0x7fa1e5002be0> { URL: http://httpbin.org/post } { status code: 200, headers {
    "Access-Control-Allow-Credentials" = true;
    "Access-Control-Allow-Origin" = "*";
    Connection = "keep-alive";
    "Content-Length" = 564;
    "Content-Type" = "application/json";
    Date = "Sat, 05 Sep 2015 07:17:06 GMT";
    Server = nginx;
} }
responseString = Optional({
  "args": {}, 
  "data": "{\"baz\":{\"b\":20,\"a\":1,\"c\":300},\"foo\":\"bar\"}", 
  "files": {}, 
  "form": {}, 
  "headers": {
    "Accept": "*/*", 
    "Accept-Encoding": "gzip, deflate", 
    "Accept-Language": "en-us", 
    "Content-Length": "42", 
    "Content-Type": "application/json", 
    "Host": "httpbin.org", 
    "User-Agent": "SVSample/1 CFNetwork/711.4.6 Darwin/14.5.0"
  }, 
  "json": {
    "baz": {
      "a": 1, 
      "b": 20, 
      "c": 300
    }, 
    "foo": "bar"
  }, 
  "origin": "118.151.1.242", 
  "url": "http://httpbin.org/post"
}
)

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