Swift崩溃中的HTTP Post请求

时间:2015-09-05 06:38:03

标签: ios xcode swift post request

出于某种原因,每次尝试发出POST请求时,我的代码都会中断。

我的代码是:

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

我继续从线路发送到调试器:
let task = NSURLSession.sharedSession()。dataTaskWithRequest(request)

我不确定我在这里做错了什么,我们将不胜感激。

1 个答案:

答案 0 :(得分:1)

我试图获得上述请求,但无法得到任何回复。 (我使用https://www.getpostman.com/

如果您想收到回复,我建议您使用https://httpbin.org/

这是有效的例子。

function val(){

    var uname = document.getElementById('username').value;
    if(!uname){
        document.getElementById("error").innerHTML = "Enter a username";
        return false;
    }
    else{
        // I want to submit form if this else statement executes.
    }


}

输出就像这样,

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