ios -网络

网络请求的两种方式:get VS post

1 get :–是获取指定URL上的资源

–将数据按照variable=value的形式,添加到action所指向的URL后面,并且两者使用“?”连接,各个变量之间使用“&”连接
–不安全,因为在传输过程中,数据被放在请求的URL中
2 post–是对指定资源“追加/添加”数据
–将数据放在数据体中,按照变量和值相对应的方式,传递到action所指向URL
–所有数据对用户来说不可见
-由于要向服务器发送数据,服务器解析后进行数据返回,相对服务器来说数不安全的
3 在默认的情况下网络请求是get 
 
二>网络请求的步骤:
第一步:确定地址url
第二部:建立请求
第三版 :建立并启动连接
 
第四部:连接完成,处理结果
 
三。网络请求中常用的类
nsurl(地址)
nsurlrequest(get 请求)
{保存需要传给web服务器的全部数据:一个nsurl  缓存 等待相应 时间,请求头,请求体}
 
nsmutableurlrequest(post请求)
nsurlconnection(连接)
{负责创建客户端和web之间的网络连接,发送 nsurlrequest对象中的数据并搜集来之服务器的响应}
 
四》nsurlConnectionDataDelegate的常用代理方法
//服务器开始返回数据
-(void)connection:didReceiveResponse:.....
//收到服务器返回的数据
-(void)connection:didReceiveData:...
//数据接受完毕
-(void)connectionDidFinishLoading:。。。
//网络连接的错误
-(void)connection:didFailWithError:
 
5.实战中get请求步骤
//定义url
NSString *stringurl=@"http://xxxxxx?userName=123&pwd=12";
//对字符串进行地址提取
NSURL *url=[NSURL URLWithString:[stringurl stringByAddimgPercentEscapesUsingEncoding]];
 
//定义请求
NSURLRequest *request=[NSURLRequest requestWithURL:url];
 
//建立连接
NSURLConnection *conn=[NSUTLConnection alloc]initWithrequestWithURL:url];
//启动
[conn start];
 
 
post 请求步骤
NSString *urlstr=@"xxxxxxxxx";
 
//定义request
NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url];
//等待服务器相应
[request setTImeoutInterval:5.0];
//设置请求方式
[request setHTTPMethod:@"post"];
NSStirng *bodString=[NSSting string WithFormat:@"username=%@ psd=%@",xx,xx];
//生成请求体数据并编码
NSData *body=[bodyString dataUsingEncoding:NSUTF8StringEncoding];
//设置http请求体数据
[request setHTTPBody:body];
 
 
原文地址:https://www.cnblogs.com/qiaojiu9/p/3362454.html