先驗知識——什麼是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);
- }
是打印服務器返回的響應信息。