How to send POST and GET request?
Asked Answered
C

4

49

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.

Chad answered 6/10, 2011 at 10:34 Comment(0)
C
135

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.

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

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:

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

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.

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

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 .

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

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

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

Update: sendSynchronousRequest is deprecated from and (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);

Chad answered 17/7, 2012 at 3:48 Comment(10)
Clean. +1. @Aleksander AziziOrientate
In my case, I've to use GET and also send json data. Can I add HTTPBody?Agincourt
I am getting requestReply to Null. What will be issue?Besought
It's most likely a bad request or server side data failure.Chad
Hi, how can we send input parameters by using above code ? please let me know.Tetrafluoroethylene
Hi @AleksanderAzizi great answer, I am wondering though, how would you insert data into a certain field within a JSON object? for example I want I have an object called "Player" and a field called "Name" and I want to only update the name, how would I do that?Crowther
@Agincourt With a GET request you include the data in the header and/or url. A GET request does not include a body.Chad
Thank u so much, After trying so much of ways, I ended my task with your solution. :-)Osana
Can you explain the code of using NSURLConnection instead of URLSession in swift.Gob
@KayCee NSURLConnection's functions for Loading Data Asynchronously are deprecated. See Apple's documentation on NSURLConnection.Chad
C
2

By using RestKit you can make a simple POST request (see this GitHub page for more details).

Import RestKit in your header file.

#import <RestKit/RestKit.h>

Then you can start by creating a new RKRequest.

RKRequest *MyRequest = [[RKRequest alloc] initWithURL:[[NSURL alloc] initWithString:@"http://myurl.com/FakeUrl/"]];

Then specify what kind of request you want to make (in this case, a POST request).

MyRequest.method = RKRequestMethodPOST;
MyRequest.HTTPBodyString = YourPostString;

And then set your request as a JSON in additionalHTTPHeaders.

MyRequest.additionalHTTPHeaders = [[NSDictionary alloc] initWithObjectsAndKeys:@"application/json", @"Content-Type", @"application/json", @"Accept", nil];

Finally, you can send the request.

[MyRequest send];

Additionally you can NSLog your request to see the outcome.

RKResponse *Response = [MyRequest sendSynchronously];
NSLog(@"%@", Response.bodyAsString);

Sources: RestKit.org and Me.

Chad answered 12/6, 2012 at 14:36 Comment(0)
S
1
 -(void)postmethod
    {

        NSString * post =[NSString stringWithFormat:@"Email=%@&Password=%@",_txt_uname.text,_txt_pwd.text];

        NSData *postdata= [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
        NSString *postLength=[NSString stringWithFormat:@"%lu",(unsigned long)[postdata length]];
        NSMutableURLRequest *request= [[NSMutableURLRequest alloc]init];

        NSLog(@"%@",app.mainurl);

       // NSString *str=[NSString stringWithFormat:@"%@Auth/Login",app.mainurl];
        NSString *str=YOUR URL;
        [request setURL:[NSURL URLWithString:str]];
        [request setHTTPMethod:@"POST"];
        [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
        [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
        [request setHTTPBody:postdata];
        NSError *error;
        NSURLResponse *response;

        NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
        NSString *returnstring=[[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
        NSMutableDictionary *dict=[returnstring JSONValue];

        NSLog(@"%@",dict);

        }

-(void)GETMethod
{
NSString *appurl;
    NSString *temp =@"YOUR URL";
    appurl = [NSString stringWithFormat:@"%@uid=%@&cid=%ld",temp,user_id,(long)clubeid];
    appurl = [appurl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:appurl]];
    NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse: nil error: nil ];
    NSString  *returnString = [[NSString alloc] initWithData:returnData encoding: NSUTF8StringEncoding];
    NSMutableDictionary *dict_eventalldata=[returnString JSONValue];
    NSString *success=[dict_eventalldata objectForKey:@"success"];
}
Shambles answered 7/9, 2015 at 10:9 Comment(0)
A
-2

view control.h

@interface ViewController     UIViewController<UITableViewDataSource,UITableViewDelegate>

  @property (weak, nonatomic) IBOutlet UITableView *tableView;
  @property (strong,nonatomic)NSArray *array;
  @property NSInteger select;
  @end

view.m

  - (void)viewDidLoad {
 [super viewDidLoad];
 NSString *urlString = [NSString stringWithFormat:    @"https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=11.021459,76.916332&radius=2000&types=atm&sensor=false&key=AIzaS yD7c1IID7zDCdcfpC69fC7CUqLjz50mcls"];
 NSURL *url = [NSURL URLWithString: urlString];
 NSData *data = [NSData dataWithContentsOfURL:url];
 NSDictionary *jsonData = [NSJSONSerialization JSONObjectWithData:      
 data options: 0 error: nil];
 _array = [[NSMutableArray alloc]init];
 _array = [[jsonData objectForKey:@"results"] mutableCopy];
[_tableView reloadData];}
// Do any additional setup after loading the view, typically from a         



 - (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
  }
 - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

return 1;
  }

  - (NSInteger)tableView:(UITableView *)tableView
  numberOfRowsInSection:(NSInteger)section {

 return _array.count;
  }

 - (UITableViewCell *)tableView:(UITableView *)tableView
     cellForRowAtIndexPath:(NSIndexPath *)indexPath {

 static NSString *cellid = @"cell";
 UITableViewCell *cell = [tableView
                         dequeueReusableCellWithIdentifier:cellid];
 cell = [[UITableViewCell
         alloc]initWithStyle:UITableViewCellStyleSubtitle
        reuseIdentifier:cellid];

 cell.textLabel.text = [[_array
 valueForKeyPath:@"name"]objectAtIndex:indexPath.row]; 
 cell.detailTextLabel.text = [[_array 
 valueForKeyPath:@"vicinity"]objectAtIndex:indexPath.row];
 NSURL *imgUrl = [NSURL URLWithString:[[_array
 valueForKey:@"icon"]objectAtIndex:indexPath.row]];  
 NSData *imgData = [NSData dataWithContentsOfURL:imgUrl];
 cell.imageView.layer.cornerRadius =        
 cell.imageView.frame.size.width/2;
 cell.imageView.layer.masksToBounds = YES;
 cell.imageView.image = [UIImage imageWithData:imgData];

 return cell;
 }

 @end

tablecell.h

 @interface TableViewCell : UITableViewCell
 @property (weak, nonatomic) IBOutlet UIImageView *imgView;
 @property (weak, nonatomic) IBOutlet UILabel *lblName;
 @property (weak, nonatomic) IBOutlet UILabel *lblAddress;
Andantino answered 8/5, 2017 at 9:11 Comment(1)
above coding is for get methodAndantino

© 2022 - 2024 — McMap. All rights reserved.