如何在Swift中创建一个Http get并设置http Header?

时间:2015-01-07 07:01:05

标签: ios http swift

我尝试在Objective-C中创建HTTP Get。

它使用NSMutableURLRequest *request;中的Objective-C,并使用[request setHTTPMethod:@"GET"];选择GETPOST

通过以下代码设置标题:

[request setValue:@"Application/json" forHTTPHeaderField:@"Accept"];
[request addValue:@"Application/json" forHTTPHeaderField:@"Content-Type"];
[request addValue:[NSString stringWithFormat:@"Basic %@",USER_PWD] forHTTPHeaderField:@"Authorization"];

我引用了链接How to make an HTTP request in Swift?,它只显示以下代码:

let url = NSURL(string: "http://www.stackoverflow.com")
let request = NSURLRequest(URL: url)

NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) {(response, data, error) in
    println(NSString(data: data, encoding: NSUTF8StringEncoding))
}

但它没有选择GetPost,也没有设置标头。 如何确定Http方法是Get还是Post?以及如何设置标题?在Swift中

提前致谢。

1 个答案:

答案 0 :(得分:13)

request.HTTPMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")