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