iOS下自带的http进行post请求,自带的json解析,自带的urldecode编码,综合体验代码:
NSString *url =@"http://ip:port/filename";
//post提交的参数,格式:id=登录名&pwd=登录密码
NSString *post = [NSString
stringWithFormat:@"id=%@&pwd=%@",@"test",@"test"];
NSLog(@"参数:%@",post);
//将NSSrring格式的参数转换格式为NSData,POST提交必须用NSData数据。
NSData *postData = [post
dataUsingEncoding:NSUTF8StringEncoding
allowLossyConversion:YES];
//计算POST提交数据的长度
NSString *postLength = [NSString
stringWithFormat:@"%ld",[postData length]];
NSLog(@"数据长度=%@",postLength);
//定义NSMutableURLRequest
NSMutableURLRequest *request = [[NSMutableURLRequestalloc] init];
[request setURL:[NSURLURLWithString:url]];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/x-www-form-urlencoded"
forHTTPHeaderField:@"Content-Type"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
//设置需要post提交的内容
[request setHTTPBody:postData];
NSHTTPURLResponse* urlResponse = nil;
NSError *error = nil;
//同步提交:POST提交并等待返回值(同步),返回值是NSData类型。
NSData *responseData = [NSURLConnection
sendSynchronousRequest:request
returningResponse:&urlResponse
error:&error];
//将NSData类型的返回值转换成NSString类型
//NSString *result = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
if (error) {
NSLog(@"提交失败,异常信息:%@",error);
}else{
NSError *err = nil;
NSDictionary *mDic = [NSJSONSerialization
JSONObjectWithData:responseData
options:NSJSONReadingMutableLeaves
error:&err];
if (err) {
NSLog(@"提交失败,反馈结果无效。");
}else{
NSRange range=[[mDic objectForKey:@"result"] rangeOfString:@"success"];
if(range.location!=NSNotFound) {
NSLog(@"字典内容:%@", mDic);
NSLog(@"余额:%@", [mDic objectForKey:@"Balance"]);
NSArray *contentLenght=[mDic objectForKey:@"ContentLenght"];
NSLog(@"内容长度限制(上限):%@", contentLenght[0]);
NSLog(@"内容长度限制(单条):%@", contentLenght[1]);
NSLog(@"内容长度限制(多条):%@", contentLenght[2]);
NSLog(@"用户:%@",
CFURLCreateStringByReplacingPercentEscapesUsingEncoding(
kCFAllocatorDefault,
(CFStringRef)[mDic objectForKey:@"User"],
(CFStringRef)@"!$&'()*+,-./:;=?@_~%#[]",
kCFStringEncodingGB_18030_2000));
//这里获取到的是gbk的,所以urldecode解析gbk,而不是utf8
NSLog(@"提交成功:%@", [mDic objectForKey:@"result"]);
}else{
NSLog(@"提交失败:%@", [mDic objectForKey:@"result"]);
}
}
}
反馈结果:
参数:id=test&pwd=test
数据长度=16
字典内容:{
Balance = 0;
ContentLenght = (
240,
67,
60
);
User = "%B2%E2%CA%D4";
result = success;
}
余额:0
内容长度限制(上限):240
内容长度限制(单条):67
内容长度限制(多条):60
用户:测试
提交成功:success