iOS 获取服务器数据(json)

IOS开发——NSURLConnection服务器获取数据 & 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=[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 allocinit];

    [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]; 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值