到现在你已经使用类似AFJSONRequestOperation这样的类创建了一次性的HTTP请求。另外,较低级的AFHTTPClient类是用来访问单个的web service终端。 对这个AFHTTPClient一般是给它设置一个基本的URL,然后用AFHTTPClient进行多个请求(而不是像之前的那样,每次请求的时候,都创建一个AFHTTPClient)。
AFHTTPClient同样为编码参数、处理multipart表单请求body的构造、管理请求操作和批次入队列操作提供了很强的灵活性,它还处理了整套RESTful (GET, POST, PUT, 和 DELETE), 下面我们就来试试最常用的两个:GET 和 POST.
注意: 对REST, GET和POST不清楚?看看这里比较有趣的介绍 – 我如何给妻子解释REST(.)
在WTTableViewController.h 顶部将类声明按照如下修改:
@interface WTTableViewController : UITableViewController
在 WTTableViewController.m中,找到httpClientTapped: 方法,并用下面的实现替换:
sender { UIActionSheet UIActionSheet allocdelegatedestructiveButtonTitle,; ; }
上面的方法会弹出一个action sheet,用以选择GET和POST请求。粘贴如下代码以实现action sheet中按钮对应的操作:
actionSheetactionSheet clickedButtonAtIndexbaseURL URLWithStringstringWithFormat:BaseURLString]]; dictionaryWithObjectforKey; // 2 AFHTTPClient AFHTTPClient alloc] initWithBaseURL:baseURL]; ; value; buttonIndexclient postPathparameters:parameters successself.weather = responseObject; self.title ; [self.tableView reloadData]; } failureUIAlertView UIAlertView allocmessagestringWithFormat,error] delegate:nil cancelButtonTitleotherButtonTitles; [av show]; } ]; buttonIndexclient getPathparameters:parameters successself.weather = responseObject; self.title ; [self.tableView reloadData]; } failureUIAlertView UIAlertView allocmessagestringWithFormat,error] delegate:nil cancelButtonTitleotherButtonTitles; [av show]; } ]; } }
上面的代码作用如下:
在这里,将请求一个JSON回应,当然也可以使用之前讨论过的另外两种格式来代替JSON。
生成并运行工程,点击HTTPClient按钮,然后选择GET 或 POST按钮来初始化一个相关的请求。之后会看到如下内容:
至此,你已经知道AFHTTPClient最基本的使用方法。不过,这里还有更好的一种使用方法,它可以让代码更加干净整齐,下面我们就来学习一下吧。 连接到Live Service
到现在为止,你已经在table view controller中直接调用了AFRequestOperations 和 AFHTTPClient. 实际上,大多数时候不是这样的,你的网络请求会跟某个web service或API相关。
AFHTTPClient已经具备与web API通讯的所有内容。AFHTTPClient在代码中已经把网络通讯部分做了解耦处理,让网络通讯的代码在整个工程中都可以重用。
下面是两个关于AFHTTPClient最佳实践的指导:
当前,你的工程中还没有一个AFHTTPClient的子类,下面就来创建一个吧。我们来处理一下,让代码清洁起来。
首先,在工程中创建一个新的文件:iOSCocoa TouchObjective-C Class. 命名为WeatherHTTPClient 并让其继承自AFHTTPClient.
你希望这个类做3件事情:
A:执行HTTP请求
B:当有新的可用天气数据时,调用delegate
C:使用用户当前地理位置来获得准确的天气。
用下面的代码替换WeatherHTTPClient.h:
#import "AFHTTPClient.h" @protocol WeatherHttpClientDelegate; @interface WeatherHTTPClient : AFHTTPClient delegate; sharedWeatherHTTPClient; initWithBaseURLurl; updateWeatherAtLocationlocation forNumberOfDaysnumber; @end @protocol WeatherHttpClientDelegate weatherHTTPClientclient didUpdateWithWeatherweather; weatherHTTPClientclient didFailWithErrorerror; @end
在实现文件中,你将了解头文件中定义的更多相关内容。打开WeatherHTTPClient.m 并将下面的代码添加到@implementation下面:
sharedWeatherHTTPClient urlStr ; static dispatch_once_t pred; static WeatherHTTPClient *_sharedWeatherHTTPClient = nil; dispatch_once_sharedWeatherHTTPClient self allocURLWithString; return _sharedWeatherHTTPClient; } initWithBaseURLurl { self = [super initWithBaseURL:url]; self; } ; value; return self; }
sharedWeatherHTTPClient 方法使用Grand Central Dispatch(GCD)来确保这个共享的单例对象只被初始化分配一次。这里用一个base URL来初始化对象,并将其设置为期望web service响应为JSON。
将下面的方法粘贴到上一个方法的下面: