Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

http

ios

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.

like image 547
Martin Avatar asked Jan 07 '15 07:01

Martin


People also ask

How do you make HTTP requests with URLSession in Swift?

import UIKit let url = URL(string: "https://bit.ly/2LMtByx")! The next step is creating a data task, an instance of the URLSessionDataTask class. A task is always tied to a URLSession instance. To keep things simple, we ask the URLSession class for the shared singleton session object through its shared class property.

How HTTP headers are set?

The HTTP headers are used to pass additional information between the clients and the server through the request and response header. All the headers are case-insensitive, headers fields are separated by colon, key-value pairs in clear-text string format. The end of the header section denoted by an empty field header.

How do I create a network request in Swift?

Before Swift 5.5, in order to make a network request, we must use the closure-based URLSession 's dataTask(with:completionHandler:) method to trigger a request that runs asynchronously in the background. Once the network request is completed, the completion handler will give us back the result from the network request.


1 Answers

request.HTTPMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
like image 176
Abhishek Sharma Avatar answered Nov 04 '22 14:11

Abhishek Sharma