Ios之网络编程NSURLConnection

  通过NSURLConnection主要通过四个类进行网络访问:NSURL,NSURLRequest,NSMutableURLRequest,NSURLConnection

  一、基本知识

(1)NSURL:请求地址

(2)NSURLRequest:封装一个请求,保存发给服务器的全部数据,包括一个NSURL对象,请求方法、请求头、请求体....

(3)NSMutableURLRequest:NSURLRequest的子类

(4)NSURLConnection:负责发送请求,建立客户端和服务器的连接。发送NSURLRequest的数据给服务器,并收集来自服务器的响应数据

  二、功能实现

  1、/*******get方式*******/

//全局变量,接收数据
NSMutableData * requestData;

NSURL * url=[NSURL URLWithString:@"http://192.168.2.162/logo.php?userName=jereh&pwd=123"];
//通过URL建立请求
NSURLRequest * request=[NSURLRequest requestWithURL:url];
//通过NSURLConnection连接服务器,并发送请求
NSURLConnection * connection=[NSURLConnection connectionWithRequest:request delegate:self];
[connection start];
//接收到请求
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
NSLog(@"didReceiveResponse");
//在该方法中初始化data
requestData=[NSMutableData data];

}
//收到数据
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
//防止文件过大,多次追加
[requestData appendData:data];

}

//数据接收完毕
- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
NSDictionary * dic=[NSJSONSerialization JSONObjectWithData:requestData options:NSJSONReadingAllowFragments error:nil];
NSLog(@"%@",dic);

}
//传输失败
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
NSLog(@"didFailWithError");

}

2、/******post方式*******/

NSURL * url=[NSURL URLWithString:@"http://192.168.2.162/loginPost.php"];
//定义可变的请求
NSMutableURLRequest * request=[NSMutableURLRequest requestWithURL:url];
//设置请求方式
request.HTTPMethod=@"POST";
//设置请求参数
request.HTTPBody=[@"userName=jereh&pwd=123" dataUsingEncoding:NSUTF8StringEncoding];

NSURLConnection * con=[NSURLConnection connectionWithRequest:request delegate:self];
[con start];

3、非代理方法

//同步
NSURLResponse * response;
NSData *  data=[NSURLConnection sendSynchronousRequest:request returningResponse: &response error:nil];
//异步
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
//主线程操作
}];
作者:杰瑞教育
出处:http://www.cnblogs.com/jerehedu/ 
版权声明:本文版权归杰瑞教育技有限公司和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
技术咨询:JRedu技术交流
 
原文地址:https://www.cnblogs.com/jerehedu/p/5068889.html