NSURLSession 请求和响应

2023-11-21

为了理解如何使用 Objective-C 中的 NSURLSession 发出 GET 请求,我想要一个例子。并且,如何获得响应?


GET

NSMutableURLRequest *urlRequest = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"give your url here"]];

//create the Method "GET" 
[urlRequest setHTTPMethod:@"GET"];

NSURLSession *session = [NSURLSession sharedSession];

NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:urlRequest completionHandler:^(NSData *data, NSURLResponse *response, NSError *error)
{
  NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
  if(httpResponse.statusCode == 200)
  {
    NSError *parseError = nil;
    NSDictionary *responseDictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:&parseError];
    NSLog(@"The response is - %@",responseDictionary);
  }
  else
  {
    NSLog(@"Error");     
  }
}];
[dataTask resume];
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

NSURLSession 请求和响应 的相关文章

随机推荐