-(void)post:(NSString *)headurl body:(NSString *)body method:(NSString *)method delegate:(
(id<DoneRequestDelegate>)delegate
{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0), ^{
//将NSSrring格式的参数转换格式为NSData,POST提交必须用NSData数据。
NSData *postData = [bodydataUsingEncoding:NSUTF8StringEncodingallowLossyConversion:YES];
//计算POST提交数据的长度
NSString *postLength = [NSStringstringWithFormat:@"%d",[postDatalength]];
//定义NSMutableURLRequest
NSMutableURLRequest *request = [[[NSMutableURLRequestalloc] init] autorelease];
NSString *url=[[NSStringalloc]initWithFormat:@"%@%@",BASEURL,headurl];
//设置提交目的url
[requestsetURL:[NSURLURLWithString:url]];
[urlrelease];
//设置提交方式为 POST
[requestsetHTTPMethod:method];
//设置http-header:Content-Type。
[request setValue:@"application/json"forHTTPHeaderField:@"Content-Type"];
[requestsetValue:postLength forHTTPHeaderField:@"Content-Length"];
//设置需要post提交的内容
[requestsetHTTPBody:postData];
//定义
NSHTTPURLResponse* urlResponse = nil;
NSError *error = [[NSErroralloc] init];
//同步提交:POST提交并等待返回值(同步),返回值是NSData类型。
NSData *responseData = [NSURLConnectionsendSynchronousRequest:request returningResponse:&urlResponse error:&error];
//将NSData类型的返回值转换成NSString类型
NSString * result = [[NSStringalloc] initWithData:responseDataencoding:NSUTF8StringEncoding];
NSLog(@"user login check result:%@",result);
dispatch_async(dispatch_get_main_queue (), ^{
if (responseData==nil) {
[alertShow alert:@"请求失败,请检查网络"];
return ;
}
[delegate DoneRequest:[self parseData:result]];
[resultrelease];
});
});
}
-(NSDictionary *)parseData:(NSString *)retString
{
//将json对象转为字典类型
NSMutableDictionary *result = [retString objectFromJSONString];
return result;
}