Objective-C-使用NSMutableURLRequest发送POST请求,使用NSJSONSerialization解析JSON字符串
2013-11-21 20:31
435 查看
NSString *reqData = @"Data="; NSData *postDatas = nil; NSString *urlPath = @"url"; //组json字符串数据 NSMutableDictionary *mulDic = [[[NSMutableDictionary alloc] init] autorelease]; [mulDic setValue:@"P003" forKey:@"type"]; //NSJSONSerialization 组json字符串 if ([NSJSONSerialization isValidJSONObject:mulDic]) { postDatas = [NSJSONSerialization dataWithJSONObject:mulDic options:NSJSONWritingPrettyPrinted error:nil]; NSString *str = [[NSString alloc] initWithData:postDatas encoding:NSUTF8StringEncoding]; reqData = [reqData stringByAppendingString:str]; NSLog(@"reqData:%@",reqData); //NSData *postData = [reqData dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES]; postDatas = [NSData dataWithBytes:[reqData UTF8String] length:[reqData length]]; } NSString *len = [NSString stringWithFormat:@"%d",(int)[postDatas length]]; NSURL *url = [NSURL URLWithString:urlPath]; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; [request setHTTPMethod:@"POST"]; //[request setValue:@"*/*" forKey:@"accept"]; //[request setValue:@"Keep-Alive" forKey:@"connection"]; //[request setValue:@"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)" forKey:@"user-agent"]; //[request setValue:len forHTTPHeaderField:@"Content-Length"]; //[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"]; [request setHTTPBody:postDatas]; NSData *retData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil]; NSString *ret = [[NSString alloc] initWithData:retData encoding:NSUTF8StringEncoding]; NSLog(@"%@",ret); //解析返回的数据JSON格式字符串 NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:retData options:NSJSONReadingMutableLeaves error:nil]; NSLog(@"%@",dic);
相关文章推荐
- Objective-C-使用NSMutableURLRequest发送POST请求,使用NSJSONSerialization解析JSON字符串
- 使用NSMutableURLRequest发送json数据
- 77 NSMutableURLRequest常用设置 GET和POST比较 发送JSON给服务器
- 基于Swift的iOS应用程序开发:使用NSMutableURLRequest向服务器发送请求
- 在线聊天项目1.4版 使用Gson方法解析Json字符串以便重构request和response的各种请求和响应 解决聊天不畅问题 Gson包下载地址
- 使用apache的httpclient发送post请求传送和解析json
- 如何使用webmagic发送post请求,并解析传回的JSON
- 使用NSMutableURLRequest和NSURLConnection 以Post方式上传照片
- NSMutableURLRequest实现Post请求及其timeoutInterval不生效问题解决
- Volley使用JsonObjectRequest发送Post请求失败
- AS3中使用URLRequest发送POST请求
- IOS成长之路-NSMutableURLRequest实现Post请求
- POST上传文件之分类抽取——以后只需要把分类导入,使用NSMutableURLRequest的分类即可
- Volley使用JsonObjectRequest发送Post请求失败
- NSMutableURLRequest 发送同步请求get方法
- Volley使用JsonObjectRequest发送Post请求失败
- 在线聊天项目1.4版 使用Gson方法解析Json字符串以便重构request和response的各种请求和响应 解决聊天不畅问题 Gson包下载地址
- JS获取url参数,JS发送json格式的POST请求方法
- NSMutableURLRequest POST数据实现
- NSMutableURLRequest,在POST方式下传递参数