1:在github上下载
https://github.com/yjxsf8313/asi-http-request
2:引入
1)在项目下新建一个Group,命名为ASIHttp,鼠标右击,选中“Add files to ....”,将下载的ASIHttprequest库中的class文件夹都引用进来,并将Externl文件夹中的Reachability添加到class下。留下ASIWebPageRequest这个文件夹,其他的都删掉
2)添加ASIHttprequest的依赖Frameworks:SystemConfiguration.framework, MobileCoreServices.framework,
CFNetwork.framework和libz.dylib,libxml2.dylib这几个类库。
3)解决ASIHttpRequest类库不支持ARC:选中项目target,在Build Phases中选Compile Source,将ASIHttpRequest的文件都改成:“-fno-objc-arc”
4)解决“libxml/HTMLparser.h' file not found”问题:
这个问题是因为你的开发环境默认的路径无法找到这个libxml2.dylib框架,修改方法:
点击左边项目的根目录,再点击右边的Build Settings,输入文字:“Header search paths”,然后单击“ Header search paths ”右边的空白处,输入:${SDK_DIR}/usr/include/libxml2
3:同步请求、异步请求
- (IBAction)grabURL:(id)sender { NSURL *url = [NSURL URLWithString:@"http://waibo.sinaapp.com/"]; //a:用requestWithURL方法获取ASIHTTPRequest的一个实例 ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url]; //b:startSynchronous方法启动同步访问 [request startSynchronous]; //c:由于是同步请求,没有基于事件的回调方法,所以从request的error属性获取错误信息 NSError *error = [request error]; if (!error) { NSString *response = [request responseString]; //d:responseString为请求返回的NSString信息 NSLog(@"%@", response); } } /*异步请求至少要添加两个回调方法来获取异步事件 a:与上面不同的是指定了一个"delegate",并用startAsynchronous来启动网络请求 b:实现了两个delegate的方法,当数据请求成功时会调用requestFinished,请求失败会调用requestFailed */ - (IBAction)grabURLInBackground:(id)sender { NSURL *url = [NSURL URLWithString:@"http://waibo.sinaapp.com/"]; ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url]; [request setDelegate:self]; [request startAsynchronous]; } - (void)requestFinished:(ASIHTTPRequest *)request { //Use when fetching text data NSString *responseString = [request responseString]; //Use when fetching binary data NSData *responseData = [request responseData]; NSLog(@"%@", responseString); } - (void)requestFailed:(ASIHTTPRequest *)request { NSError *error = [request error]; NSLog(@"%@", error); }
4:队列请求
/*队列请求:提供了一个对异步请求更加精准丰富的控制。 如可以设置在队列中,同步请求的连接数。往队列里添加的请求实例数大于maxConcurrentOperationCount时,请求实例将被设置为等待,直到前面至少有一个请求完成并出列才被放到队列里执行 也适用于当我们有多个请求需要按顺序执行的时候(可能是业务上的需要,也可能是软件上调优),仅仅需要把maxConcurrentOperationCount设为1 */ - (IBAction)grabURLInTheBackground:(id)sender { if (![self queue]) { [self setQueue:[[NSOperationQueue alloc] init]]; NSURL *url = [NSURL URLWithString:@"http://www.baidu.com"]; //a:请求队列上下文。可设置一个上下文(如userInfo)到request对象中,当请求响应完后可以通过访问request对象的userinfo获取里面的信息 ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url]; [request setDelegate:self]; //b:为每个请求实例设置不同的setDidFinisheSelector / setDidFailSelector的回调方法 [request setDidFinishSelector:@selector(requestDone:)]; [request setDidFailSelector:@selector(requestWentWrong:)]; [[self queue] addOperation:request]; } } - (void)requestDone:(ASIHTTPRequest *)request { NSString *response = [request responseString]; NSLog(@"%@", response); } - (void)requestWentWrong:(ASIHTTPRequest *)requeset { NSError *error = [requeset error]; NSLog(@"%@", error); }