iOS开发实践之GET和POST请求

GET和POST请求是HTTP请求方式中最最为常见的。

在说请求方式之前先熟悉HTTP的通信过程:

请求

1、请求行 :
请求方法、请求路径、HTTP协议的版本号

GET /MJServer/resources/images/1.jpg HTTP/1.1

2、请求头 : client的一些描写叙述信息

Host: 192.168.1.111:8080
// client想訪问的server主机地址

     User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.9) Firefox/30.0   //
client的类型,client的软件环境

      Accept: text/html,
// client所能接收的数据类型

      Accept-Language: zh-cn
// client的语言环境

      Accept-Encoding: gzip
// client支持的数据压缩格式

3、请求体 : POST请求才有这个东西

请求參数,发给server的数据

响应

1、状态行(响应行): HTTP协议的版本号、响应状态码、响应状态描写叙述

Server: Apache-Coyote/1.1
// server的类型

       Content-Type: image/jpeg
// 返回数据的类型

       Content-Length: 56811
// 返回数据的长度

        Date: Mon, 23 Jun 2014 12:54:52 GMT
// 响应的时间

2、 响应头:server的一些描写叙述信息

Content-Type : server返回给client的内容类型

Content-Length : server返回给client的内容的长度(比方文件的大小)

3、 实体内容(响应体)

server返回给client详细的数据,比方文件数据

NSMutableURLRequest(注意:非NSURLRequest 由于这个对象是不可变的)

1、设置超时时间(默认60s)

request.timeoutInterval =
15;

2、设置请求方式

request.HTTPMethod =
@"POST";

3、设置请求体

request.HTTPBody = data;

4、设置请求头  比如例如以下是传JSON数据的表头设置

[request setValue:@"application/json"
forHTTPHeaderField:@"Content-Type"];

GET和POST对照:

GET(默认情况是get请求):

特点:GET方式提交的參数直接拼接到url请求地址中。多个參数用&隔开。比如:http://localhost:8080/myService/login?username=123&pwd=123

缺点:

1、在url中暴露了全部的请求数据,不太安全

2、因为浏览器和server对URL长度有限制,因此在URL后面附带的參数是有限制的,通常不能超过1KB

- (IBAction)login {
NSString *loginUser = self.userName.text;
NSString *loginPwd = self.pwd.text;
if (loginUser.length==0) {
[MBProgressHUD showError:@"请输入用户名!"];
return;
} if (loginPwd.length==0) {
[MBProgressHUD showError:@"请输入password。"];
return;
} // 添加蒙板
[MBProgressHUD showMessage:@"正在登录中....."]; //默认是get方式请求:get方式參数直接拼接到url中
NSString *urlStr = [NSString stringWithFormat:@"http://localhost:8080/myService/login?username=%@&pwd=%@",loginUser,loginPwd]; //post方式请求,參数放在请求体中
//NSString *urlStr = @"http://localhost:8080/myService/login"; //URL转码
urlStr = [urlStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]]; //urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; NSURL *url = [NSURL URLWithString:urlStr]; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; //设置超时时间(默认60s)
request.timeoutInterval = 15; //设置请求方式
request.HTTPMethod = @"POST"; //设置请求体
NSString *param = [NSString stringWithFormat:@"username=%@&pwd=%@", loginUser,loginPwd];
// NSString --> NSData
request.HTTPBody = [param dataUsingEncoding:NSUTF8StringEncoding]; // 设置请求头信息
[request setValue:@"iphone" forHTTPHeaderField:@"User-Agent"]; [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
//隐藏蒙板
[MBProgressHUD hideHUD];
if(connectionError || data==nil){
[MBProgressHUD showError:@"网络繁忙! 稍后再试。"];
return ;
}else{
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
NSString *error = dict[@"error"];
if (error) {
[MBProgressHUD showError:error];
}else{
NSString *success = dict[@"success"];
[MBProgressHUD showSuccess:success];
}
}
}]; }

POST

特点:

1、把全部请求參数放在请求体(HTTPBody)中

2、理论上讲。发给server的数据的大小是没有限制

3、请求数据相对安全(没有绝对的安全)

 // 1.URL
NSURL *url = [NSURL URLWithString:@"http://localhost:8080/myService/order"]; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; request.timeoutInterval = 15;
request.HTTPMethod = @"POST"; NSDictionary *orderInfo = @{
@"shop_id" : @"1111",
@"shop_name" : @"的地方地方",
@"user_id" : @"8919"
};
NSData *json = [NSJSONSerialization dataWithJSONObject:orderInfo options:NSJSONWritingPrettyPrinted error:nil];
request.HTTPBody = json; // 5.设置请求头:这次请求体的数据不再是普通的參数,而是一个JSON数据
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
if(connectionError || data==nil){
[MBProgressHUD showError:@"网络繁忙!稍后再试! "];
return ;
}else{
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
NSString *error = dict[@"error"];
if (error) {
[MBProgressHUD showError:error];
}else{
NSString *success = dict[@"success"];
[MBProgressHUD showSuccess:success];
}
}
}];

url转码问题(URL中不能包括中文)

1、这方法已过时

NSString *urlStr = [NSString stringWithFormat:@"http://localhost/login?username=喝喝&pwd=123"];
urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

2、官方推荐使用:

NSString *urlStr = [NSString stringWithFormat:@"http://localhost/login?username=喝喝&pwd=123"];
urlStr = [urlStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
上一篇:S - Query on a tree HDU - 3804 线段树+dfs序


下一篇:Android开发:碎片Fragment完全解析fragment_main.xml/activity_main.xml