Martin
Martin

Reputation: 2863

How to make a Http get and set httpHeader in Swift?

I have try to make a HTTP Get in Objective-C.

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"];

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

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

Thanks in advance.

Upvotes: 7

Views: 17017

Answers (1)

Abhishek Sharma
Abhishek Sharma

Reputation: 3283

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

Upvotes: 16

Related Questions