简单的objective-c GET请求

时间:2012-02-22 22:24:52

标签: objective-c http get

这里的大部分信息都是指废弃的ASIHTTPREQUEST项目,请原谅我再次询问。

实际上,我需要刷磁条并将曲目2数据发送到返回“已登记”或“未登记”的网络服务(取决于卡的状态......)

所以我的数据就像

一样
NSData *data = [notification object];

然后我需要将其传递给

的网址

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

然后只收到一个响应字符串......

我搜索了很多,似乎有一些相互矛盾的答案,是否应该只使用AFNetworking,RESTkit或本机NSURL / NSMutableURLRequest协议来完成。

4 个答案:

答案 0 :(得分:59)

在Objective-C中执行HTTP请求的选项可能有点令人生畏。一个对我有用的解决方案是使用NSMutableURLRequest。一个例子(使用ARC,所以YMMV)是:

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

<强>更新

您的问题的标题和标记说POST,但您的示例网址会指示GET请求。在GET请求的情况下,上面的示例就足够了。对于POST,您可以按如下方式进行更改:

- (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 */ 
}

答案 1 :(得分:14)

iOS 9更新: 因此,从iOS 9开始不推荐使用[NSURLConnection sendSynchronousRequest]。以下是从iOS 9开始使用NSURLSession执行GET请求的方法

获取请求

// 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请求

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

答案 2 :(得分:1)

经过100%工作测试

仅适用于目标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];
}

答案 3 :(得分:0)

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