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.
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.
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.
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.
request.HTTPMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With