如何在Swift中创建一个Http get并设置httpHeader? [英] How to make a Http get and set httpHeader in Swift?
问题描述
我尝试在Objective-C中创建HTTP Get。
I have try to make a HTTP Get in Objective-C.
它使用 NSMutableURLRequest *请求; in
Objective-C
,并使用 [request setHTTPMethod:@GET];
选择 GET
或 POST
。
It use the NSMutableURLRequest *request;
in Objective-C
, and use [request setHTTPMethod:@"GET"];
to select GET
or POST
.
并通过以下代码设置标题:
And set the Header via following code:
[request setValue:@"Application/json" forHTTPHeaderField:@"Accept"];
[request addValue:@"Application/json" forHTTPHeaderField:@"Content-Type"];
[request addValue:[NSString stringWithFormat:@"Basic %@",USER_PWD] forHTTPHeaderField:@"Authorization"];
我引用链接如何在Swift中发出HTTP请求?,它只显示以下代码:
I reference the link How to make an HTTP request in Swift?, and it only show the following code:
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))
}
但它没有选择获取
或发布
,它也没有设置标题。
如何判断Http方法获取
或发布
?以及如何设置标题?在Swift中
But it didn't select Get
or Post
, and it also didn't set the header.
How to decide the Http method is Get
or Post
? and how to set the Header? in Swift
提前致谢。
推荐答案
request.HTTPMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
这篇关于如何在Swift中创建一个Http get并设置httpHeader?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!