iOS网络请求http之NSURLConnection简单同步请求

NSURLConnection是负责发送请求,建立客户端和服务器的连接。发送数据给服务器,并接受来自服务器的响应数据。

使用NSURLConnection发送请求的分3步

(1)创建一个NSURL对象,设置请求路径

(2)传入NSURL创建一个NSURLRequest对象,设置请求头和请求体,请求超时...(创建请求对象)

(3)使用NSURLConnection发送NSURLRequest(发送请求)

NSURLConnection提供了两种发送网络请求的方法,分别是

1、同步请求,返回data数据,会卡主UI主线程。

+ (nullable NSData *)sendSynchronousRequest:(NSURLRequest *)request returningResponse:(NSURLResponse * __nullable * __nullable)response error:(NSError **)error;

2、异步请求,数据通过block返回,不卡主线程。

+ (void)sendAsynchronousRequest:(NSURLRequest*) request

queue:(NSOperationQueue*) queue

completionHandler:(void (^)(NSURLResponse* __nullable response, NSData* __nullable data, NSError* __nullable connectionError)) handler;

3、对应代码

// 创建一个URL :请求路径

NSString *urlStr = [NSString stringWithFormat:@"http://xxx.com"];

NSURL *url = [NSURL URLWithString:urlStr];

// 创建一个请求,默认为GET请求

NSURLRequest *request = [NSURLRequest requestWithURL:url];

// 发送一个同步请求(在主线程发送请求)

NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];

一个简单的NSURLConnection的同步请求的demo。请点击这里

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容