Objective-C——NSMutableURLRequest发送POST请求,使用NSJSONSerialization解析JSON字符串

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);

  

转载于:https://www.cnblogs.com/LeoMabi/p/5112644.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值