异步请求HTTP
2023-09-11 14:15:06 时间
代码:
@interface HttpProcessor : NSObject <NSURLConnectionDataDelegate> { NSMutableData *buffer; } @property BOOL finished; @property (strong, nonatomic) NSString *html; @end @implementation HttpProcessor @synthesize finished; @synthesize html; -(id)init { if (self) { finished = NO; } return self; } // 开始接收响应 -(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { finished = NO; buffer = [[NSMutableData alloc] init]; } // 接收ing , 可能多次调用 -(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { [buffer appendData:data]; } // 结束响应 -(void)connectionDidFinishLoading:(NSURLConnection *)connection { finished = YES; html = [[NSString alloc] initWithData:buffer encoding:NSUTF8StringEncoding]; //NSLog(@"%@", html); NSLog(@"OK"); } @end void request(NSString *urlString) { NSLog(@"BEGIN"); // make request object NSURL *url = [[NSURL alloc]initWithString:urlString]; NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:url]; [request setHTTPMethod:@"GET"]; [request setTimeoutInterval:10]; // send request HttpProcessor *processor = [[HttpProcessor alloc]init]; [NSURLConnection connectionWithRequest:request delegate:processor]; }
代码块:
void request(NSString *urlString) { NSLog(@"BEGIN"); // make request object NSURL *url = [[NSURL alloc]initWithString:urlString]; NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:url]; [request setHTTPMethod:@"GET"]; [request setTimeoutInterval:10]; // send request [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler: ^(NSURLResponse *response, NSData *result, NSError *error) { //只会进入一次,方法内部已经实现了Buffer作用 NSString *html = [[NSString alloc] initWithData:result encoding:NSUTF8StringEncoding]; NSLog(@"html = %@", html); } ]; }
参考:
http://www.tuicool.com/articles/2Yru6f
相关文章
- [Web] mobx 异步操作
- 阻塞与非阻塞、同步与异步的区别
- 可以运行测试的IOS同步请求、异步请求、GET请求、POST请求
- 教你如何封装异步网络连接NSURLConnection实现带有百分比的下载
- [Http] Understand what an HTTP Request is
- 解决docker push镜像到私有仓库时的报错【http: server gave HTTP response to HTTPS client】
- 再谈IO的异步,同步,阻塞和非阻塞
- Atitit 获取ip的http标头 目录 1.1. REMOTE_ADDR 是你的客户端跟你的服务器“握手”时候的IP1 1.2. HTTP_CLIENT_IP 客户ip。握手ip1 1.3
- Atitit 微服务实践 艾提拉著 微服务主要解决几个问题负载均很 目录 1. 微服务的模式 http请求层 vs服务层1 1.1. Http vs 服务层优缺点1 2. 实现技术2
- Atitit.异步编程技术原理与实践attilax总结
- 【Android 异步操作】AsyncTask 异步任务 ( AsyncTask 异步任务执行方法 execute 方法相关源码解析 )
- 异步通信之 信号
- CSharp(C#)语言_高级篇(异步编程)【划重点咯】
- HTTP隧道ABPTTS——加密型的http隧道,todo自己搭建一个玩玩
- 思科恶意加密TLS流检测论文记录——由于样本不均衡,其实做得并不好,神马99.9的准确率都是浮云啊,之所以思科使用DNS和http一个重要假设是DGA和HTTP C&C(正常http会有图片等)。一开始思科使用的逻辑回归,后面17年文章是随机森林。
- vue3 watch 异步方法