Simple objective-c GET request

后端 未结 4 1590
栀梦
栀梦 2020-12-13 04:17

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 th

相关标签:
4条回答
  • 2020-12-13 04:50

    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];
    }
    
    0 讨论(0)
  • 2020-12-13 05:04

    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 */ 
    }
    
    0 讨论(0)
  • 2020-12-13 05:06

    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];
    
    0 讨论(0)
  • 2020-12-13 05:15
    **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];
    }
    
    0 讨论(0)
提交回复
热议问题