iOS 獲取伺服器資料(json)
NSData *res = request.responseData; NSError *error; NSDictionary *json = [NSJSONSerialization JSONObjectWithData:res options:NSJSONReadingMutableLeaves error:&error]; if (error) { NSLog(@"%@",error);
}
關於引數:options
NSJSONReadingMutableContainers:Specifies that arrays and dictionaries are created as mutable objects.返回的容器是可變型別的(Array和Dictionary) NSJSONReadingMutableLeaves: Specifies that leaf strings in the JSON object graph are created as instances of NSMutableString.
返回的葉子NSString是可變型別的; NSJSONReadingAllowFragments: Specifies that the parser should allow top-level objects that are not an instance of NSArray or NSDictionary. 允許頂層的介面不是NSArray或NSDictionary; 如果都不需要,預設填0。
範例
1. 同步方式:
url = [NSString stringWithFormat:@"http://192.168.1.24/netoffice/passwordcheck.jsp?Account=%@&Password=%@&rand=%@", username, password, randcode]; request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:url] cachePolicy:NSURLCacheStorageAllowed timeoutInterval:10]; NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error]; if (responseData) { … … }
2. 非同步方式1:
[NSURLConnection sendAsynchronousRequest:hotWordsRequest queue:operationQueue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) { if (error) { NSLog(@"error:\n%@",error); return; } NSDictionary *json = [NSJSONSerializationJSONObjectWithData:data options:0error:&error]; NSLog(@"%@",json); }];
3. 非同步方式2:
1.建立NSConnection物件,設定委託物件 NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:[self urlString]]]; [NSURLConnection connectionWithRequest:request delegate:self]; 2. NSURLConnection delegate委託方法
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response; - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error; - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data; - (void)connectionDidFinishLoading:(NSURLConnection *)connection; 3. 實現委託方法 - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { // store data [self.receivedData setLength:0]; //通常在這裡先清空接受資料的快取 } - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { [self.receivedData appendData:data]; //可能多次收到資料,把新的資料新增在現有資料最後 } - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { // 錯誤處理 } - (void)connectionDidFinishLoading:(NSURLConnection *)connection { // disconnect [UIApplication sharedApplication].networkActivityIndicatorVisible = NO; NSString *returnString = [[NSString alloc] initWithData:self.receivedData encoding:NSUTF8StringEncoding]; NSLog(returnString); [self urlLoaded:[self urlString] data:self.receivedData]; firstTimeDownloaded = YES; }
3.ASIHTTPRequest的使用:
- (void)getSearchHotWordsFromSender:(PSearchViewController *) searchViewController{ NSURL *url = [NSURLURLWithString:PaperSearchHotWordsUrl]; ASIHTTPRequest *hotWordsRequest = [ASIHTTPRequestrequestWithURL:url]; self.currentConnectionRequest = hotWordsRequest; [hotWordsRequest setDelegate:searchViewController]; [hotWordsRequest setDidFinishSelector:@selector(hotWordsRequestFinished:)]; [hotWordsRequest setDidFailSelector:@selector(hotWordsRequestFailed:)]; [hotWordsRequest setRequestMethod:@"GET"]; //設定超時時間 [hotWordsRequest setTimeOutSeconds:ConnectionTimeOutSeconds]; //保持cookie的狀態 //[hotWordsRequest setUseCookiePersistence:NO]; //發出非同步請求 [hotWordsRequest startAsynchronous]; } 回撥處理: - (void)hotWordsRequestFinished:(ASIHTTPRequest *)request{ NSError *error; NSDictionary *json = [NSJSONSerializationJSONObjectWithData:request.responseDataoptions:0error:&error]; if (error) { NSLog(@"%@",error); } … ... } - (void)hotWordsRequestFailed:(ASIHTTPRequest *)request{ … … }
////////////////------------------------------------------------------
//1.建立post方式的 引數字串url
+(NSString *)createPostURL:(NSMutableDictionary *)params
{
NSString *postString=@"";
for(NSString *key in [params allKeys])
{
NSString *value=[params objectForKey:key];
postString=[postString stringByAppendingFormat:@"%@=%@&",key,value];
}
if([postString length]>1)
{
postString=[postString substringToIndex:[postString length]-1];
}
return postString;
}
//2.zwh -自定義的通用方法------post資料回伺服器,並返回結果資料集
+(NSData *)getResultDataByPost:(NSMutableDictionary *)params
{
NSString *postURL=[Utility createPostURL:params];
NSError *error;
NSURLResponse *theResponse;
NSMutableURLRequest *theRequest=[NSMutableURLRequestrequestWithURL:[NSURLURLWithString:BASEURL]];
[theRequest setHTTPMethod:@"POST"];
[theRequest setHTTPBody:[postURL dataUsingEncoding:NSUTF8StringEncoding]];
[theRequest addValue:@"application/x-www-form-urlencoded"forHTTPHeaderField:@"Content-Type"];
return [NSURLConnectionsendSynchronousRequest:theRequest returningResponse:&theResponse error:&error];
}
//呼叫例項程式碼
NSMutableDictionary *params=[[NSMutableDictionaryalloc] init];
[params setObject:@"taobao.taobaoke.items.get"forKey:@"method"];
[params setObject:@"num_iid,title,pic_url,price,score"forKey:@"fields"];
[params setObject:@"淘寶帳戶" forKey:@"nick"];
[params setObject:selectedItemCat.cid forKey:@"cid"];
[params setObject:@"true"forKey:@"is_mobile"];
NSData *resultData=[Utility getResultData:params];