NSURLConnection常用类:
NSURL:用于设置请求地址
NSURLRequest:用于封装一个请求,保=保存发给服务器的全部数据,包括NSURL对象,请求方式,请求头以及请求体等,默认请求方式是GET
NSMutableURLRequest:是NSURLRequest的子类,常用方法有:
设置请求超时等待时间:-(void)setTimeoutInterval:(NSTimeInterval)second;
设置请求方式:-(void)setHTTPMethod:(NSString *)method; (GET或POST)
设置请求体:-(void)setHTTPBody:(NSData *)data;
设置请求头:-(void)setValue:(NSString *)value forHTTPHeaderField:(NSString *)field;
NSURLConnection
负责发送请求,建立客户端和服务器之间的连接,发送NSURLRequest的数据给服务器,并收集来自服务器的相应数据
使用步骤:
1、创建NSURL对象,设置请求路径
2、传入NSURL创建一个NSURLRequest对象,设置请求头和请求体(创建请求对象)
3、使用NSURLConnection发送NSURLRequest (发送请求)
同步请求:
//同步请求
-(void)sync {
//1.创建NSURL对象
NSURL *url = [NSURLURLWithString:@"https://tieba.baidu.com/?page=user"];
//2.创建NSURLRequest默认请求方式是GET
NSURLRequest *request = [NSURLRequestrequestWithURL:url];
//3.使用NSURLConnection发送请求
/*
Response:响应头
error:错误信息
data:返回数据
*/
NSURLResponse *response =nil;
NSError *error =nil;
NSData *data = [NSURLConnectionsendSynchronousRequest:requestreturningResponse:&responseerror:&error];
if (error ==nil) {
NSLog(@"--响应头-%@---",response);
//请求成功
NSString *string = [[NSStringalloc] initWithData:dataencoding:NSUTF8StringEncoding];
NSLog(@"---返回信息-%@----",string);
}else {
NSLog(@"--错误信息-%@---",error);
}
}
二、异步请求——使用block
-(void)async {
//block回调
//1.NSURL对象
NSURL *url = [NSURLURLWithString:@"https://tieba.baidu.com/?page=user"];
//2.NSURLRequest
//queue: 运行的线程
NSURLRequest *request = [NSURLRequestrequestWithURL:url];
[NSURLConnectionsendAsynchronousRequest:requestqueue:[NSOperationQueuemainQueue] completionHandler:^(NSURLResponse *_Nullable response, NSData * _Nullable data,NSError * _Nullable connectionError) {
if (connectionError ==nil) {
NSLog(@"---响应头--%@", response);
NSString *str = [[NSStringalloc]initWithData:dataencoding:NSUTF8StringEncoding ];
NSLog(@"---%@---", str);
}else {
NSLog(@"error=%@", connectionError);
}
NSLog(@"currentThread=%@",[NSThreadcurrentThread]);
}];
}
//遵守NSURLConnectionDataDelegate协议
@interface ViewController ()<NSURLConnectionDataDelegate>
//创建数据容器,接收所有数据
@property (nonatomic ,strong)NSMutableData *data;
@end
//异步请求--delegate
-(void)asycn_delegate {
//1.NSURL对象
NSURL *url = [NSURLURLWithString:@"https://tieba.baidu.com/?page=user"];
//2.NSURLRequest
NSURLRequest *request = [NSURLRequestrequestWithURL:url];
//3.发送请求
[NSURLConnectionconnectionWithRequest:requestdelegate:self];
}
#pragma mark -协议方法
//连接错误
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(@"error = %@", error);
}
//接收到响应
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
NSLog(@"%@",response);
if (self.data) {
//将以前数据清空
self.data.length =0;
}else {
self.data = [[NSMutableDataalloc] init];
}
}
//接收到数据如果数据量大那么就是分段接收该方法可能会调用多次
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
NSLog(@"---%zd---",data.length);
//在数句容器里面拼接数据
[self.dataappendData:data];
}
//请求成功
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(@"connectionDidFinishLoading");
//解析数据
NSString *str = [[NSStringalloc] initWithData:self.dataencoding:NSUTF8StringEncoding];
NSLog(@"-数据--%@--",str);
}
//POST请求
-(void)post {
// 1. 创建一个URL对象
NSURL *url = [NSURL URLWithString:@"https://tieba.baidu.com/"];
//2.
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
// 修改请求方式:
request.HTTPMethod = @"POST";
//在请求体中,添加请求数据
request.HTTPBody = [@"page=user" dataUsingEncoding:NSUTF8StringEncoding];
//3.发送请求
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
if (connectionError == nil) {
NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"%@",str);
//解析JSON
NSArray *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
NSLog(@"data = %@",dic);
}else {
NSLog(@"---%@---",connectionError);
}
}];
}