如何在iOS中发送Get请求?

时间:2011-06-02 09:04:00

标签: iphone objective-c url get nsurl

我正在创建一个库来获取具有指定数据和方法类型的特定URL的响应。为此,我正在使用url提出请求。但是当我设置它的方法类型时,它会在[NSURLRequest setHTTPMethod:]中显示无法识别的选择器发送的异常 我将其设置为

[requestObject setHTTPMethod:@"GET"];

告诉我可能是什么问题。如果你有,也请提供代码。

4 个答案:

答案 0 :(得分:82)

NSMutableURLRequest *request = 
[NSMutableURLRequest requestWithURL:[NSURL 
            URLWithString:serverAddress] 
            cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData
                                                   timeoutInterval:10
 ];

[request setHTTPMethod: @"GET"];

NSError *requestError = nil;
NSURLResponse *urlResponse = nil;


NSData *response1 =
        [NSURLConnection sendSynchronousRequest:request
                         returningResponse:&urlResponse error:&requestError];

答案 1 :(得分:12)

NSString *getString = [NSString stringWithFormat:@"parameter=%@",yourvalue];
NSData *getData = [getString dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *getLength = [NSString stringWithFormat:@"%d", [getData length]];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:@"https:yoururl"]];
[request setHTTPMethod:@"GET"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:getData];
self.urlConnection = [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
NSAssert(self.urlConnection != nil, @"Failure to create URL connection.");
// show in the status bar that network activity is starting [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;

答案 2 :(得分:2)

确保您的requestObject类型为NSMutableURLRequest

答案 3 :(得分:2)

只需致电并使用:

(void)jsonFetch{

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