IOS开发——NSURLConnection服务器获取数据 & JSON数据解析
接口说明
NSData *res = request.responseData; NSError *error; NSDictionary *json = [NSJSONSerialization JSONObjectWithData:res options:NSJSONReadingMutableLeaves error:&error]; if (error) { NSLog(@"%@",error);
}
关于参数:options
范例
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=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:BASEURL]];
[theRequest setHTTPMethod:@"POST"];
[theRequest setHTTPBody:[postURL dataUsingEncoding:NSUTF8StringEncoding]];
[theRequest addValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
return [NSURLConnection sendSynchronousRequest:theRequest returningResponse:&theResponse error:&error]; }
//调用实例代码 NSMutableDictionary
*params=[[NSMutableDictionary alloc] 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];