Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send POST and GET request?

I want to send my JSON to a URL (POST and GET).

NSMutableDictionary *JSONDict = [[NSMutableDictionary alloc] init]; [JSONDict setValue:"myValue" forKey:"myKey"];  NSData *JSONData = [NSJSONSerialization dataWithJSONObject:self options:kNilOptions error:nil]; 

My current request code isn't working.

NSMutableURLRequest *requestData = [[NSMutableURLRequest alloc] init];  [requestData setURL:[NSURL URLWithString:@"http://fake.url/"];];  [requestData setHTTPMethod:@"POST"]; [requestData setValue:postLength forHTTPHeaderField:@"Content-Length"]; [requestData setValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; [requestData setValue:@"application/json" forHTTPHeaderField:@"Accept"]; [requestData setHTTPBody:postData]; 

Using ASIHTTPRequest is not a liable answer.

like image 596
Aleksander Azizi Avatar asked Oct 06 '11 10:10

Aleksander Azizi


People also ask

Can I use POST for GET request?

POST is valid to use instead of GET if you have specific reasons for doing so and process it properly.

What is a POST vs GET request?

GET retrieves a representation of the specified resource. POST is for writing data, to be processed to the identified resource. 2. It typically has relevant information in the URL of the request.

How GET and POST requests work?

HTTP POST requests supply additional data from the client (browser) to the server in the message body. In contrast, GET requests include all required data in the URL. Forms in HTML can use either method by specifying method="POST" or method="GET" (default) in the <form> element.


1 Answers

Sending POST and GET requests in iOS is quite easy; and there's no need for an additional framework.


POST Request:

We begin by creating our POST's body (ergo. what we'd like to send) as an NSString, and converting it to NSData.

objective-c

NSString *post = [NSString stringWithFormat:@"test=Message&this=isNotReal"]; NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES]; 

Next up, we read the postData's length, so we can pass it along in the request.

NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]]; 

Now that we have what we'd like to post, we can create an NSMutableURLRequest, and include our postData.

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init]; [request setURL:[NSURL URLWithString:@"http://YourURL.com/FakeURL"]]; [request setHTTPMethod:@"POST"]; [request setValue:postLength forHTTPHeaderField:@"Content-Length"]; [request setHTTPBody:postData]; 

swift

let post = "test=Message&this=isNotReal" let postData = post.data(using: String.Encoding.ascii, allowLossyConversion: true)  let postLength = String(postData!.count)  var request = URLRequest(url: URL(string: "http://YourURL.com/FakeURL/PARAMETERS")!) request.httpMethod = "POST" request.addValue(postLength, forHTTPHeaderField: "Content-Length") request.httpBody = postData; 

And finally, we can send our request, and read the reply by creating a new NSURLSession:

objective-c

NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]]; [[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {     NSString *requestReply = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];     NSLog(@"Request reply: %@", requestReply); }] resume]; 

swift

let session = URLSession(configuration: .default) session.dataTask(with: request) {data, response, error in     let requestReply = NSString(data: data!, encoding: String.Encoding.ascii.rawValue)     print("Request reply: \(requestReply!)") }.resume() 

GET Request:

With the GET request it's basically the same thing, only without the HTTPBody and Content-Length.

objective-c

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init]; [request setURL:[NSURL URLWithString:@"http://YourURL.com/FakeURL/PARAMETERS"]]; [request setHTTPMethod:@"GET"];  NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]]; [[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {     NSString *requestReply = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];     NSLog(@"Request reply: %@", requestReply); }] resume]; 

swift

var request = URLRequest(url: URL(string: "http://YourURL.com/FakeURL/PARAMETERS")!) request.httpMethod = "GET"  let session = URLSession(configuration: .default) session.dataTask(with: request) {data, response, error in     let requestReply = NSString(data: data!, encoding: String.Encoding.ascii.rawValue)     print("Request reply: \(requestReply!)") }.resume() 

On a side note, you can add Content-Type (and other data) by adding the following to our NSMutableURLRequest. This might be required by the server when requesting, e.g, a json.

objective-c

[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; [request setValue:@"application/json" forHTTPHeaderField:@"Accept"]; 

Response code can also be read using [(NSHTTPURLResponse*)response statusCode].

swift

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

Update: sendSynchronousRequest is deprecated from ios9 and osx-elcapitan (10.11) and out.

NSURLResponse *requestResponse; NSData *requestHandler = [NSURLConnection sendSynchronousRequest:request returningResponse:&requestResponse error:nil]; NSString *requestReply = [[NSString alloc] initWithBytes:[requestHandler bytes] length:[requestHandler length] encoding:NSASCIIStringEncoding]; NSLog(@"requestReply: %@", requestReply); 

like image 105
Aleksander Azizi Avatar answered Sep 22 '22 13:09

Aleksander Azizi