iOS项目开发实战——使用AFNetworking进行Http Get请求

     只要是做开发,就一定会接触到网络请求。AFNetworking是目前为止,iOS开源代码中排名第一的库,从来没有停止过更。提供的人性化API可以为我们做网络相关开发节省很多时间。我先来使用AFNetworking来进行Http Get请求。

Http 请求包含三部分(请求格式):请求方法(GET,POST)、请求头(HttpHeaderFields)、请求正文(数据)。

(1)新建一个iOS项目,语言选择OC,然后导入AFNetworking的库,可以从云盘上下载  http://pan.baidu.com/s/1gdrqxe7 。直接把里面的三个文件夹拖入到项目中即可。

(2)然后在代码中实现如下:

- (void)viewDidLoad {
  [super viewDidLoad];
  
  
  // http://api.openweathermap.org/data/2.5/forecast/daily?lat=39.907501&lon=116.397232&cnt=10
  
  // http://h.hiphotos.baidu.com/image/pic/item/8d5494eef01f3a298a1c0a799c25bc315d607cb5.jpg
  
  
  NSString *urlStr = @"http://api.openweathermap.org/data/2.5/forecast/daily?lat=39.907501&lon=116.397232&cnt=10";
  
  
  AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
  
  // 设置回复内容信息
  manager.responseSerializer.acceptableContentTypes = [manager.responseSerializer.acceptableContentTypes setByAddingObject:@"text/html"];
  
  [manager GET:urlStr
    parameters:nil
       success:^(AFHTTPRequestOperation *operation, id responseObject) {
         
         NSLog(@"%@",responseObject);
         
       }
       failure:^(AFHTTPRequestOperation *operation, NSError *error) {
         
         NSLog(@"%@",error);
         
       }];
  
  
  
}

(3)运行程序,可以看到控制台中打印出返回数据,表示使用AFNetworking请求网络数据成功。

(4)如果要进行POST请求,只要把代码中的GET改为POST,经过测试,也能返回数据,表示该网站同时支持GET和POST。



github主页:https://github.com/chenyufeng1991  。欢迎大家访问!

你可能感兴趣的:(iOS开发,iOS开发技术分享)