How to send a Get request in iOS?

2019-01-13 05:01发布

问题:

I am making a library to get response from a particular URL with specified data and method type. For this, I am making a request with url. But when I set its method type, it shows an exception of unrecognized selector send in [NSURLRequest setHTTPMethod:] I am setting it as

[requestObject setHTTPMethod:@"GET"];

Tell me what could be the problem. Also provide me the code if you have.

回答1:

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


回答2:

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;



回答3:

Make sure your requestObject is of type NSMutableURLRequest.



回答4:

Simply call and use:

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