ios中调用webservice获得json格式的数据

第一步,组装json格式的请求参数,得到 jsonData

   //创建json格式的请求参数

    NSError *error = NULL;

    NSDictionary *info = [NSDictionary dictionaryWithObjectsAndKeys:

    [txt_ text],@"id",

     @"from iphone",@"description"

    , nil];

    //将NSDictionary格式的数据压缩NSData格式,同时编码成UTF8格式

    NSData *jsonData = [NSJSONSerialization

    dataWithJSONObject:info

    options:NSJSONWritingPrettyPrinted

    error:&error];


第二步,请求webservice接口(封装为函数):

 //直接在里面获取到数据并处理即可

-(void)insertCatalogWithJson:(NSData*)json

{

      NSString *urlAsString = [[NSString alloc]initWithString: [kWSLookingFunURL absoluteString]];

      urlAsString = [urlAsString stringByAppendingString:@"?action=insert"];

      //将string类型url的请求参数封装为NSURL

      NSURL *url = [NSURL URLWithString:urlAsString];

      

      NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];

      [urlRequest setTimeoutInterval:30.0f];

      [urlRequest setHTTPMethod:@"POST"];

      //直接把NSData(此时的编码为UTF8)做为请求参数

      [urlRequest setHTTPBody:json];

      NSLog(@"REQUEST: %@", [urlRequest HTTPBody]);

      NSOperationQueue *queue = [[NSOperationQueue alloc] init];

 

      [NSURLConnection

      sendAsynchronousRequest:urlRequest

      queue:queue

      completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {

           if ([data length] >0 && error == nil)

           {

              //获得到数据

              NSString *html = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];

              NSLog(@"HTML = %@", html);

              //重新从WebService读取资料

              // [self wsLookingFun];

           }else if ([data length] == 0 && error == nil)

           {

              NSLog(@"Nothing was downloaded.");

           }else if (error != nil)

           {

              NSLog(@"Error happened = %@", error);

           }

     }];

}

第三步,调用函数即可:

       [self insertCatalogWithJson:jsonData];


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值