NSURLConnection网络请求,是苹果自带的类。现在用的比较少了,一般都是用第三方框架,但是内部的实现还是通过NSURLConnection或者NSURLSession(是对前者的封装)实现的;所以说还是需要了解;
网络请求现在基本分为两类:Get和Post,Get一般用来获取数据,Post用上传数据;NSURLConnection默认的是Get;
Get的请求体都是和URL用'?'连接;而Post都是存在请求体中;并且请求体的大小没有限制;
首先在创建网络连接时;需要地址(URL),请求(NSURLRequest);最后才是连接网络请求;
//确定请求路径
NSURL *url = [NSURL URLWithString:@"http://连接地址"];
//创建请求对象
NSURLRequest *request = [NSURLRequest requestWithURL:url];
/*
如果需要更改请求方法:
request.HTTPMethod = @"POST";
拼接请求体:
NSString *param = [NSString stringWithFormat:@"username=%@&pwd=%@",self.userName.text,self.pwd.text];
设置请求体
request.HTTPBody = [param dataUsingEncoding:NSUTF8StringEncoding];
*/
//3.发送请求
//请求分为异步发送和同步发送;
/*同步请求,需要传递响应头地址和错误信息储存地址;而且有服务器返回的,需要接收;
NSURLResponse *response = nil; //这是创建的响应头;
NSError *error = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
*/
/*异步请求:参数1:请求;参数2:回调的队列;参数3:请求完成后需要执行的操作;
[NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc]init] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
if (connectionError) {
}else {
// NSHTTPURLResponse是响应头实际的类型;statusCode是响应的状态:200:成功,500:服务器故障,404:找不到资源,400:客户端访问错误;
NSHTTPURLResponse *respon = (NSHTTPURLResponse *)response;
NSLog(@"%zd--%@",respon.statusCode,respon.allHeaderFields);
//4.解析响应体;
NSString *res = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"%@---%@",res,[NSThread currentThread]);
}
}];
//设置代理,发送异步请求,可以做一些监测,需要实现代理方法;
//第一种方法:
//[NSURLConnection connectionWithRequest:request delegate:self];
//第二种方法:
// NSURLConnection *connt = [[NSURLConnection alloc]initWithRequest:request delegate:self];
//第三种方法:和第二种唯一的区别是不会马上提交连接;需要手动开启;
NSURLConnection *connt = [[NSURLConnection alloc]initWithRequest:request delegate:self startImmediately:NO];
[connt start];
*/
代理方法使用,相信根据参数名字,很容易知道是什么时候调用的:
//1.当接收到服务器响应的时候调用
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
NSLog(@"---didReceiveResponse-");
}
//2.当接收到服务器返回数据的时候调用,接收的数据不是一次性接收;
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
NSLog(@"---didReceiveData-%zd",data.length);
}
//3.当请求结束之后调用
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(@"---connectionDidFinishLoading-");
}
//4.当请求失败之后调用
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(@"---didFailWithError-");
}