先验知识——什么是ASIHTTPRequest?php
使用iOS SDK中的HTTP网络请求API,至关的复杂,调用很繁琐,ASIHTTPRequest就是一个对CFNetwork API进行了封装,而且使用起来很是简单的一套API,用Objective-C编写,能够很好的应用在Mac OS X系统和iOS平台的应用程序中。ASIHTTPRequest适用于基本的HTTP请求,和基于REST的服务之间的交互。json
如何使用ASIHTTPRequest?服务器
上传JSON格式数据网络
首先给出主功能代码段,而后对代码进行详细解析:app
- NSDictionary *user = [[NSDictionary alloc] initWithObjectsAndKeys:@"0", @"Version", nil];
- if ([NSJSONSerialization isValidJSONObject:user])
- {
- NSError *error;
- NSData *jsonData = [NSJSONSerialization dataWithJSONObject:user options:NSJSONWritingPrettyPrinted error: &error];
- NSMutableData *tempJsonData = [NSMutableData dataWithData:jsonData];
- //NSLog(@"Register JSON:%@",[[NSString alloc] initWithData:tempJsonData encoding:NSUTF8StringEncoding]);
-
- NSURL *url = [NSURL URLWithString:@"http://42.96.140.61/lev_version.php"];
- ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
- [request addRequestHeader:@"Content-Type" value:@"application/json; encoding=utf-8"];
- [request addRequestHeader:@"Accept" value:@"application/json"];
- [request setRequestMethod:@"POST"];
- [request setPostBody:tempJsonData];
- [request startSynchronous];
- NSError *error1 = [request error];
- if (!error1) {
- NSString *response = [request responseString];
- NSLog(@"Test:%@",response);
- }
- }
代码段第一行:ide
- NSDictionary *user = [[NSDictionary alloc] initWithObjectsAndKeys:@"0", @"Version", nil];
构造了一个最简单的字典类型的数据,由于自iOS 5后提供把NSDictionary转换成JSON格式的API。url
第二行if判断该字典数据是否能够被JSON化。utf-8
- NSData *jsonData = [NSJSONSerialization dataWithJSONObject:user options:NSJSONWritingPrettyPrinted error: &error];
这一句就是把NSDictionary转换成JSON格式的方法,JSON格式的数据存储在NSData类型的变量中。同步
- NSMutableData *tempJsonData = [NSMutableData dataWithData:jsonData];
这一句是把NSData转换成NSMutableData,缘由是下面咱们要利用ASIHTTPRequest发送JSON数据时,其消息体必定要以NSMutableData的格式存储。it
下面一句注视掉的语句
- //NSLog(@"Register JSON:%@",[[NSString alloc] initWithData:tempJsonData encoding:NSUTF8StringEncoding]);
主要做用是记录刚才JSON格式化的数据
下面到了ASIHTTPRequest功能部分:
- NSURL *url = [NSURL URLWithString:@"http://xxxx"];
- ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
这两句的主要功能是设置要与客户端交互的服务器端地址。
接下来两句:
- [request addRequestHeader:@"Content-Type" value:@"application/json; encoding=utf-8"];
- [request addRequestHeader:@"Accept" value:@"application/json"];
是设置HTTP请求信息的头部信息,从中能够看到内容类型是JSON。
接下来是设置请求方式(默认为GET)和消息体:
- [request setRequestMethod:@"POST"];
- [request setPostBody:tempJsonData];
一切设置完毕后开启同步请求:
- [request startSynchronous];
最后的一段:
- if (!error1) {
- NSString *response = [request responseString];
- NSLog(@"Rev:%@",response);
- }
是打印服务器返回的响应信息。