Simple objective-c GET request

╄→гoц情女王★ 提交于 2019-12-17 22:15:02

问题


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:


Tested 100% working

Only for Objective C

-(void)fetchData
{

    NSURLSessionConfiguration *defaultSessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];
    NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration:defaultSessionConfiguration];

    // Setup the request with URL
    NSURL *url = [NSURL URLWithString:@"https://test.orgorg.net/ios/getStory.php?"];
    NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];

    // Convert POST string parameters to data using UTF8 Encoding
    NSString *postParams = @"";
    NSData *postData = [postParams dataUsingEncoding:NSUTF8StringEncoding];

    // Convert POST string parameters to data using UTF8 Encoding
    [urlRequest setHTTPMethod:@"POST"];
    [urlRequest setHTTPBody:postData];

    // Create dataTask
    NSURLSessionDataTask *dataTask = [defaultSession dataTaskWithRequest:urlRequest completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {

        NSDictionary *results = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
        //JSON Parsing....
        NSString *message = results[@"Message"];
        BOOL status = results[@"Status"];
        if (status){
           // Here you go for data....

        }else{
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"App"
                                                                           message:message
                                                                    preferredStyle:UIAlertControllerStyleAlert]; // 1
            UIAlertAction *firstAction = [UIAlertAction actionWithTitle:@"Ok"
                                                                  style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
                                                                      NSLog(@"You pressed button one");
                                                                  }]; // 2


            [alert addAction:firstAction]; // 4

            [self presentViewController:alert animated:YES completion:nil];
        }



    }];

    // Fire the request
    [dataTask resume];
}



回答4:


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


来源:https://stackoverflow.com/questions/9404104/simple-objective-c-get-request

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!