黑马程序员技术交流社区

标题: 使用NSMutableURLRequest发送POST请求,使用NSJSONSerialization解析JSON... [打印本页]

作者: UT丶    时间: 2014-5-8 12:22
标题: 使用NSMutableURLRequest发送POST请求,使用NSJSONSerialization解析JSON...
  1.     NSString *reqData = @"Data=";
  2.     NSData *postDatas = nil;
  3.     NSString *urlPath = @"url";
  4.    
  5.     //组json字符串数据
  6.     NSMutableDictionary *mulDic = [[[NSMutableDictionary alloc] init] autorelease];
  7.     [mulDic setValue:@"P003" forKey:@"type"];
  8.    
  9.     //NSJSONSerialization 组json字符串
  10.     if ([NSJSONSerialization isValidJSONObject:mulDic]) {
  11.         
  12.         postDatas = [NSJSONSerialization dataWithJSONObject:mulDic options:NSJSONWritingPrettyPrinted error:nil];
  13.         NSString *str = [[NSString alloc] initWithData:postDatas encoding:NSUTF8StringEncoding];
  14.         reqData = [reqData stringByAppendingString:str];
  15.         NSLog(@"reqData:%@",reqData);
  16.         
  17.         //NSData *postData = [reqData dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
  18.         postDatas = [NSData dataWithBytes:[reqData UTF8String] length:[reqData length]];
  19.         
  20.     }
  21.    
  22.     NSString *len = [NSString stringWithFormat:@"%d",(int)[postDatas length]];
  23.     NSURL *url = [NSURL URLWithString:urlPath];
  24.     NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
  25.     [request setHTTPMethod:@"POST"];
  26.     //[request setValue:@"*/*" forKey:@"accept"];
  27.     //[request setValue:@"Keep-Alive" forKey:@"connection"];
  28.     //[request setValue:@"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)" forKey:@"user-agent"];
  29.     //[request setValue:len forHTTPHeaderField:@"Content-Length"];
  30.     //[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
  31.     [request setHTTPBody:postDatas];
  32.    
  33.     NSData *retData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
  34.     NSString *ret = [[NSString alloc] initWithData:retData encoding:NSUTF8StringEncoding];
  35.     NSLog(@"%@",ret);<pre code_snippet_id="76577" snippet_file_name="blog_20131121_1_3817688" name="code" class="cpp">    //解析返回的数据JSON格式字符串
  36.     NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:retData options:NSJSONReadingMutableLeaves error:nil];
  37.     NSLog(@"%@",dic);</pre>
  38. <pre></pre>
  39. <pre></pre>
  40. <pre></pre>
复制代码







欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2