先驗知識——什么是ASIHTTPRequest?
使用iOS SDK中的HTTP網絡請求API,相當的復雜,調用很繁瑣,ASIHTTPRequest就是一個對CFNetwork API進行了封裝,并且使用起來非常簡單的一套API,用Objective-C編寫,可以很好的應用在Mac OS X系統和iOS平臺的應用程序中。ASIHTTPRequest適用于基本的HTTP請求,和基于REST的服務之間的交互。
上傳JSON格式數據
首先給出主功能代碼段,然后對代碼進行詳細解析:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
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); } } |
代碼段第一行:
1
|
NSDictionary *user = [[NSDictionary alloc] initWithObjectsAndKeys:@ "0" , @ "Version" , nil]; |
構造了一個最簡單的字典類型的數據,因為自iOS 5后提供把NSDictionary轉換成JSON格式的API。
第二行if判斷該字典數據是否可以被JSON化。
1
|
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:user options:NSJSONWritingPrettyPrinted error: &error]; |
這一句就是把NSDictionary轉換成JSON格式的方法,JSON格式的數據存儲在NSData類型的變量中。
1
|
NSMutableData *tempJsonData = [NSMutableData dataWithData:jsonData]; |
這一句是把NSData轉換成NSMutableData,原因是下面我們要利用ASIHTTPRequest發送JSON數據時,其消息體一定要以NSMutableData的格式存儲。
下面一句注視掉的語句
1
|
//NSLog(@"Register JSON:%@",[[NSString alloc] initWithData:tempJsonData encoding:NSUTF8StringEncoding]); |
主要作用是記錄剛才JSON格式化的數據
下面到了ASIHTTPRequest功能部分:
1
2
|
NSURL *url = [NSURL URLWithString:@ "http://xxxx" ]; ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url]; |
這兩句的主要功能是設置要與客戶端交互的服務器端地址。
接下來兩句:
1
2
|
[request addRequestHeader:@ "Content-Type" value:@ "application/json; encoding=utf-8" ]; [request addRequestHeader:@ "Accept" value:@ "application/json" ]; |
是設置HTTP請求信息的頭部信息,從中可以看到內容類型是JSON。
接下來是設置請求方式(默認為GET)和消息體:
1
2
|
[request setRequestMethod:@ "POST" ]; [request setPostBody:tempJsonData]; |
一切設置完畢后開啟同步請求:
1
|
[request startSynchronous]; |
最后的一段:
1
2
3
4
|
if (!error1) { NSString *response = [request responseString]; NSLog(@ "Rev:%@" ,response); } |
是打印服務器返回的響應信息。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:http://blog.csdn.net/yuanbohx/article/details/10343179