永发信息网

iOS怎样发送同步和异步HTTP Request

答案:1  悬赏:0  手机版
解决时间 2021-01-08 13:12
iOS怎样发送同步和异步HTTP Request
最佳答案
1. 同步发送

- (NSString *)sendRequestSync
{
// 初始化请求, 这里是变长的, 方便扩展
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];

// 设置
[request setURL:[NSURL URLWithString:urlStr]];
[request setHTTPMethod:@"POST"];
[request setValue:host forHTTPHeaderField:@"Host"];
NSString *contentLength = [NSString stringWithFormat:@"%d", [content length]];
[request setValue:contentLength forHTTPHeaderField:@"Content-Length"];
[request setHTTPBody:content];

// 发送同步请求, data就是返回的数据
NSError *error = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nilerror:&error];
if (data == nil) {
NSLog(@"send request failed: %@", error);
return nil;
}

NSString *response = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"response: %@", response);
return response;
}

2.异步发送

1) 使用delegate的方式:

- (void)sendRequestAsync
{
// 初始化请求
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];

// 设置
[request setURL:[NSURL URLWithString:urlStr]];
[request setCachePolicy:NSURLRequestUseProtocolCachePolicy]; // 设置缓存策略
[request setTimeoutInterval:5.0]; // 设置超时

//......

receivedData = [[NSMutableData alloc] initData: nil];

NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if (connection == nil) {
// 创建失败
return;
}
}

异步发送使用代理的方式, 需要实现以下delegate接口:

// 收到回应
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
NSLog(@"receive the response");
// 注意这里将NSURLResponse对象转换成NSHTTPURLResponse对象才能去
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response;
if ([response respondsToSelector:@selector(allHeaderFields)]) {
NSDictionary *dictionary = [httpResponse allHeaderFields];
NSLog(@"allHeaderFields: %@",dictionary);
}
[receivedData setLength:0];
}

// 接收数据
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
NSLog(@"get some data");
[receivedData appendData:data];
}

// 数据接收完毕
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSString *results = [[NSString alloc]
initWithBytes:[receivedData bytes]
length:[receivedData length]
encoding:NSUTF8StringEncoding];

NSLog(@"connectionDidFinishLoading: %@",results);
}

// 返回错误
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(@"Connection failed: %@", error);
}

2) iOS 5.0版本新增异步发送接口:
+ (void)sendAsynchronousRequest:(NSURLRequest *)request
queue:(NSOperationQueue*) queue
completionHandler:(void (^)(NSURLResponse*, NSData*, NSError*)) handlerNS_AVAILABLE(10_7, 5_0);
我要举报
如以上问答信息为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
大家都在看
为什么有人说猫嫌贫爱富,嫌贫爱富才是人类的
日语N1怎么过
三国新装每件要多少钱60 杜康
佳能650D怎么样啊啊
广州做餐饮身高1.45厘米能去吗?
金蝶2000V7.0教学版为什么只能结账2次?请问
ppt2003官方下载
潮州歌册的现状
凯越张紧轮损坏的原因
耿记整形喷漆地址有知道的么?有点事想过去!
自己身上部位的英语单词,怎么写要给我标出来
穿越火线怎么才能买超级矮个子
27岁离婚的男生可以谈恋爱吗!晚不晚
凉拌旱藕粉丝的做法,凉拌旱藕粉丝怎么做好吃
为什么人坐在电热炕上身体有电
推荐资讯
(没法抗浓情蜜意,始终思念你,堆积起每分的
为什么下载速度正常上传速度很慢
当采用尼龙6,6 旨的时候,需要考虑哪些因素
杭州有没有什么好的英语培训机构。主要锻炼口
小狗躺在你身边摇尾巴是什么意思
北戴河南戴河在一个方向吗?
RegisterClass(&cWndclass)返回NULL getLastE
购千叶近视眼镜可打折吗?
和一个32的女的分手了,她家条件比我家好不少
汾酒53度和金六福四星哪个好喝
电调可以连接充电宝吗
开源扫盲:MySQL是完全免费软件吗
正方形一边上任一点到这个正方形两条对角线的
阴历怎么看 ?