Simple objective-c GET request

2019-01-21 20:21发布

问题:

Most of the information here refers to the abandoned ASIHTTPREQUEST project so forgive me for asking again.

Effectively, I need to swipe a magnetic strip and send the track 2 data to a webservice that returns "enrolled" or "notenrolled" (depending on the status of the card...)

So my data comes in simply as

NSData *data = [notification object];

And then I need to pass this to a url to the order of

http://example.com/CardSwipe.cfc?method=isenrolled&track2=data

And then just receive a response string...

I've searched a ton and there seems to be some conflicting answers as to whether this should be accomplished simply with AFNetworking, RESTkit, or with the native NSURL/NSMutableURLRequest protocols.

回答1:

The options for performing HTTP requests in Objective-C can be a little intimidating. One solution that has worked well for me is to use NSMutableURLRequest. An example (using ARC, so YMMV) is:

- (NSString *) getDataFrom:(NSString *)url{
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    [request setHTTPMethod:@"GET"];
    [request setURL:[NSURL URLWithString:url]];

    NSError *error = nil;
    NSHTTPURLResponse *responseCode = nil;

    NSData *oResponseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&responseCode error:&error];

    if([responseCode statusCode] != 200){
        NSLog(@"Error getting %@, HTTP status code %i", url, [responseCode statusCode]);
        return nil;
    }

    return [[NSString alloc] initWithData:oResponseData encoding:NSUTF8StringEncoding]; 
}

Update:

Your question's title, and tagging say POST, but your example URL would indicate a GET request. In the case of a GET request, the above example is sufficient. For a POST, you'd change it up as follows:

- (NSString *) getDataFrom:(NSString *)url withBody:(NSData *)body{
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    [request setHTTPMethod:@"POST"];
    [request setHTTPBody:body];
    [request setValue:[NSString stringWithFormat:@"%d", [body length]] forHTTPHeaderField:@"Content-Length"];
    [request setURL:[NSURL URLWithString:url]];

    /* the same as above from here out */ 
}


回答2:

Update for iOS 9: So, [NSURLConnection sendSynchronousRequest] is deprecated starting from iOS 9. Here's how to do a GET request using NSURLSession starting from iOS 9

GET Request

// making a GET request to /init
NSString *targetUrl = [NSString stringWithFormat:@"%@/init", baseUrl];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setHTTPMethod:@"GET"];
[request setURL:[NSURL URLWithString:targetUrl]];

[[[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:
  ^(NSData * _Nullable data,
    NSURLResponse * _Nullable response,
    NSError * _Nullable error) {

      NSString *myString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
      NSLog(@"Data received: %@", myString);
}] resume];

POST Request

// making a POST request to /init
NSString *targetUrl = [NSString stringWithFormat:@"%@/init", baseUrl];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];

//Make an NSDictionary that would be converted to an NSData object sent over as JSON with the request body
NSDictionary *tmp = [[NSDictionary alloc] initWithObjectsAndKeys:
                     @"basic_attribution", @"scenario_type",
                     nil];
NSError *error;
NSData *postData = [NSJSONSerialization dataWithJSONObject:tmp options:0 error:&error];

[request setHTTPBody:postData];
[request setHTTPMethod:@"POST"];
[request setURL:[NSURL URLWithString:targetUrl]];

[[[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:
  ^(NSData * _Nullable data,
    NSURLResponse * _Nullable response,
    NSError * _Nullable error) {

      NSString *responseStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
      NSLog(@"Data received: %@", responseStr);
}] resume];


回答3:

**Simply Call and get your JSON Data.**

-(void)getJSONData
{

NSURL *url = [NSURL URLWithString:@"http://itunes.apple.com/us/rss/topaudiobooks/limit=10/json"];

NSURLSession *session = [NSURLSession sharedSession];

NSURLSessionDataTask *data = [session dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {

    NSError *erro = nil;

    if (data!=nil) {

        NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&erro ];

        if (json.count > 0) {

            for(int i = 0; i<10 ; i++){

                [arr addObject:[[[json[@"feed"][@"entry"] objectAtIndex:i]valueForKeyPath:@"im:image"] objectAtIndex:0][@"label"]];
           }

        }
    }
    dispatch_sync(dispatch_get_main_queue(),^{

        [table reloadData];
    });
}];

[data resume];
}