iOS开发中使用NSURLConnection发送get或post请求获取接口数据非常重要,下面是NSURLConnection对象发送请求的案例,这里是同步发送get/post请求,非异步的,照着做就可以了。
方式一:发送get请求获取接口数据。
- (NSDictionary *)getGroupInfoWithGroupId:(NSString *)groupId{
NSMutableArray *mutArray = [Md5Utils md5:[groupId stringByAppendingString:@"{190E5ABD-7F47-42F1-9DBA-9E96AF601AF1}"]];
//签名数组转base64
NSString *md5Sign = [Md5Utils arrToBase64:mutArray];
//urlEncode
NSString *signdataStr = [MessageUtils urlEncodeStr:md5Sign];
//以下是发送get请求关键部分
NSString *host = @"http://218.16.122.163:2004/xfplatform-message-0.0.1-SNAPSHOT";
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@/BeeGroup/getGroupInfoByGid?signdata=%@&gid=%@",host,signdataStr,groupId]];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
NSError *erro = nil;
NSURLResponse *resp = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&resp error:&erro];
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
return dict;
}方式二:发送post请求获取接口数据。
//根据群组信息获取群信息,post请求
- (NSDictionary *)getGroupInfoWithGroupId:(NSString *)groupId{
NSMutableArray *mutArray = [Md5Utils md5:[groupId stringByAppendingString:@"{190E5ABD-7F47-42F1-9DBA-9E96AF601AF1}"]];
//签名数组转base64
NSString *md5Sign = [Md5Utils arrToBase64:mutArray];
//urlEncode
NSString *signdataStr = [MessageUtils urlEncodeStr:md5Sign];
//以下是发送post请求关键部分
NSString *urlStr = @"http://218.16.122.163:2004/xfplatform-message-0.0.1-SNAPSHOT/BeeGroup/getGroupInfoByGid?";
//post专用request
NSMutableURLRequest *mutRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlStr]];
//封装参数
NSString *paramStr = [NSString stringWithFormat:@"signdata=%@&gid=%@",signdataStr,groupId];
[mutRequest setHTTPMethod:@"POST"];
[mutRequest setHTTPBody:[paramStr dataUsingEncoding:NSUTF8StringEncoding]];
NSError *erro = nil;
NSURLResponse *resp = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:mutRequest returningResponse:&resp error:&erro];
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
return dict;
}