Simple objective-c GET request

后端 未结 4 1594
栀梦
栀梦 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 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 */ 
    }
    

提交回复
热议问题