iOS 网络请求

网络请求包括GET.POST两种方式,其步骤为:1>获取URL。 2>获取请求。 3>创建链接。 4>返回数据(代理)。

1>获取URL。

?
1
2
3
4
//当参数为中文时,用UTF8编码
//urlStr=[urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url=[NSURL URLWithString:urlStr];

2>获取请求。

?
1
NSURLRequest *request=[NSURLRequest requestWithURL:url];

默认get方法的参数只需要URL拼接。

当创建post方法的时候,对request进行如下操作

?
1
2
3
4
5
<span style= "font-size:18px;" >NSString *dataStr=[NSString stringWithFormat:@ "UserName=%@&LoginPwd=%@" ,self.QQField.text,self.pwdField.text];
NSData *data=[dataStr dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPBody:data];
[request setHTTPMethod:@ "POST" ];
[request setTimeoutInterval: 5.0 ];</span>

3>创建链接。

此时,创建的 代理为本类,所以该类必须继承协议

?
1
NSURLConnection *conn=[NSURLConnection connectionWithRequest:request delegate:self];

4>返回数据(代理)。实现代理必须实现如下方法

?
1
2
3
4
5
6
7
8
<span style= "font-size:18px;" > //网络返回数据开始
-( void )connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
//重复调用,返回数据处理
-( void )connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
//返回数据结束
-( void )connectionDidFinishLoading:(NSURLConnection *)connection
//发生错误处理方法
-( void )connection:(NSURLConnection *)connection didFailWithError:(NSError *)error</span>


IOS 提供另一种方法实现数据回传

1.同步>>

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

2.异步>>

[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(block)];


具体代码如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
<span style= "color:#333333;" ># import "CSZViewController.h"
 
@interface CSZViewController ()
 
@property (nonatomic,strong) NSMutableData *mutableData;
 
@end
 
@implementation CSZViewController
 
- ( void )viewDidLoad
{
     [ super viewDidLoad];
 
}
 
 
- (NSURLRequest *)getRequest {
     NSString *urlStr=@ "http://api.zbw.vc/api/vip/GetPhonePadTagMsg" ;
     //当参数为中文时,用UTF8编码
     //urlStr=[urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
     NSURL *url=[NSURL URLWithString:urlStr];
     
     NSURLRequest *request=[NSURLRequest requestWithURL:url];
     return request;
}
 
- (IBAction)getLogin {
     
     NSURLRequest *request = [self getRequest];
     NSURLConnection *conn=[NSURLConnection connectionWithRequest:request delegate:self];
     [conn start];
}
 
- (NSMutableURLRequest *)getAsyncRequest {
     NSString *urlStr=@ "http://api.zbw.vc/api/Vip/PostUserInfo" ;
     NSURL *url=[NSURL URLWithString:urlStr];
     NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url];
     
     NSString *dataStr=[NSString stringWithFormat:@ "UserName=%@&LoginPwd=%@" ,self.QQField.text,self.pwdField.text];
     
     NSData *data=[dataStr dataUsingEncoding:NSUTF8StringEncoding];
     
     [request setHTTPBody:data];
     [request setHTTPMethod:@ "POST" ];
     [request setTimeoutInterval: 5.0 ];
     return request;
}
 
- (IBAction)postLogin {
     
     [UIApplication sharedApplication].networkActivityIndicatorVisible=YES;
     
     NSMutableURLRequest *request = [self getAsyncRequest];
     NSURLConnection *conn=[NSURLConnection connectionWithRequest:request delegate:self];
     [conn start];
}
 
-( void )connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
     NSLog(@ "%@" ,@ "网络返回数据开始" );
}
 
-( void )connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
     if (_mutableData==nil) {
         _mutableData=[NSMutableData data];
     }
     [_mutableData appendData:data];
}
 
-( void )connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
     _mutableData=nil;
}
 
-( void )connectionDidFinishLoading:(NSURLConnection *)connection
{
     NSString *str=[[NSString alloc] initWithData:_mutableData encoding:NSUTF8StringEncoding];
     NSLog(@ "%@" ,str);
     
     if (_mutableData!=nil) {
         _mutableData=nil;
     }
     [UIApplication sharedApplication].networkActivityIndicatorVisible=NO;
}
 
- (IBAction)clickSync {
     NSURLRequest *request = [self getRequest];
     NSURLResponse *resp=nil;
     NSError *error=nil;
     NSData *data=[NSURLConnection sendSynchronousRequest:request returningResponse:&resp error:&error];
     if (error!=nil) {
         NSLog(@ "%@" ,error.localizedDescription);
         return ;
     }
     
     if (data!=nil) {
         //解码
         NSString *respStr=[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
         NSLog(@ "%@" ,respStr);
     }
     else
     {
         NSLog(@ "获取不到网络数据" );
     }
     
}
 
- (IBAction)clickAsync {
     NSURLRequest *request = [self getAsyncRequest];
     
     [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
         if (connectionError!=nil) {
             NSLog(@ "%@" ,connectionError.localizedDescription);
         } else if (response!=nil) {
             //解码
             NSString *res=[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
             NSLog(@ "%@" ,res);
         } else {
             NSLog(@ "获取不到网络数据" );
         }
     }];
     
     
}
 
@end </span>

一、GET请求和POST请求简单说明

创建GET请求

复制代码
1 //    1.设置请求路径
2     NSString *urlStr=[NSString stringWithFormat:@"http://192.168.1.53:8080/MJServer/login?username=%@&pwd=%@",self.username.text,self.pwd.text];
3     NSURL *url=[NSURL URLWithString:urlStr];
4     
5 //    2.创建请求对象
6     NSURLRequest *request=[NSURLRequest requestWithURL:url];
7     
8 //    3.发送请求
复制代码

服务器:

创建POST请求

复制代码
 1     // 1.设置请求路径
 2     NSURL *URL=[NSURL URLWithString:@"http://192.168.1.53:8080/MJServer/login"];//不需要传递参数
 3     
 4 //    2.创建请求对象
 5     NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:URL];//默认为get请求
 6     request.timeoutInterval=5.0;//设置请求超时为5秒
 7     request.HTTPMethod=@"POST";//设置请求方法
 8     
 9     //设置请求体
10     NSString *param=[NSString stringWithFormat:@"username=%@&pwd=%@",self.username.text,self.pwd.text];
11     //把拼接后的字符串转换为data,设置请求体
12     request.HTTPBody=[param dataUsingEncoding:NSUTF8StringEncoding];
13     
14 //    3.发送请求
复制代码

服务器:

二、比较

建议:提交用户的隐私数据一定要使用POST请求

相对POST请求而言,GET请求的所有参数都直接暴露在URL中,请求的URL一般会记录在服务器的访问日志中,而服务器的访问日志是黑客攻击的重点对象之一

用户的隐私数据如登录密码,银行账号等。

 

三、使用

1.通过请求头告诉服务器,客户端的类型(可以通过修改,欺骗服务器)

复制代码
 1     // 1.设置请求路径
 2     NSURL *URL=[NSURL URLWithString:@"http://192.168.1.53:8080/MJServer/login"];//不需要传递参数
 3     
 4 //    2.创建请求对象
 5     NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:URL];//默认为get请求
 6     request.timeoutInterval=5.0;//设置请求超时为5秒
 7     request.HTTPMethod=@"POST";//设置请求方法
 8     
 9     //设置请求体
10     NSString *param=[NSString stringWithFormat:@"username=%@&pwd=%@",self.username.text,self.pwd.text];
11     //把拼接后的字符串转换为data,设置请求体
12     request.HTTPBody=[param dataUsingEncoding:NSUTF8StringEncoding];
13     
14     //客户端类型,只能写英文
15     [request setValue:@"ios+android" forHTTPHeaderField:@"User-Agent"];
复制代码

服务器:

2.加强对中文的处理

问题:URL不允许写中文

在GET请求中,相关代码段打断点以验证。

在字符串的拼接参数中,用户名使用“文顶顶”.

转换成URL之后整个变成了空值。

提示:URL里面不能包含中文。

解决:进行转码

复制代码
1 //    1.设置请求路径
2     NSString *urlStr=[NSString stringWithFormat:@"http://192.168.1.53:8080/MJServer/login?username=%@&pwd=%@",self.username.text,self.pwd.text];
3    //转码
4    urlStr= [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
5     NSURL *url=[NSURL URLWithString:urlStr];
6     
7 //    2.创建请求对象
8     NSURLRequest *request=[NSURLRequest requestWithURL:url];
复制代码

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值