我们都知道请求数据时前缀会有一个http,而http请求数据时会有两种方法:GET 和 POST。
GET 和 POST的区别:
GET 特征
1.浏览器和服务器对URL长度有限制,因此在URL后面附带的参数是有限制的,通常不能超过1KB
2.会把请求的数据暴露在接口里面
POST 特征
1.参数全部放在请求体中 这样就保证了数据的安全。
2.没有具体的长度限制,唯一的限制就是服务器的承受能力
选择GET和POST的建议
(1) 如果要传输大量数据,比如文件上传,只能用post请求
(2) GET的安全性比POST差,如果包含机密/敏感信息。建议用post
(3) 如果仅仅是索取数据(数据查询),建议用GET
(4) 如果是增加,修改,删除数据,建议用POST
GET
<span style="font-size:14px;"> NSString *interfaceString = @"http://apis.baidu.com/showapi_open_bus/mobile/find";
NSString *requestContentString = @"num=18096072457";
// 准备好地址字符串 urlString
NSString *urlString = [NSString stringWithFormat:@"%@?%@",interfaceString,requestContentString];
// 把链接地址字符串转换成UTF8格式 这一步不是必须的
NSURL *url = [NSURL URLWithString:[urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
// 可变的请求 可以添加 请求方式 以及请求的请求头 或者更多
// timeoutInterval 请求所需的时间 超过 时间 不再发送这个请求 cachePolicy缓存内容的方式
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];
// GET 一般是大写 指定HTTP的请求方式 为GET
request.HTTPMethod = @"GET";
NSString *apiKey = @"e7f5ac9e7c42a6c8cb125ee1d7e8779e";
// 把apiKey 发送给 服务器 指定的请求头 位置
[request addValue:apiKey forHTTPHeaderField:@"apikey"];
[NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc]init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
NSLog(@"%@",response);
// 解析 json 文件
// 把 data 转换成json文件
NSDictionary *info = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
NSLog(@"%@",info);
NSLog(@"%@ %@",info[@"showapi_res_body"][@"city"],info[@"showapi_res_body"][@"name"]);
}];</span>
POST
<span style="font-size:14px;">
NSURL *url = [NSURL URLWithString:@"http://www.weihuok.com/customer2/GetService"];
// 请求的参数
// 3 表示iOS设备
NSDictionary *dic = @{@"PlatformType":@"3"};
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];
// 设置HTTP请求的方式 POST 把请求的数据放到 HTTPBody 里面
request.HTTPMethod = @"POST";
// 设置请求的参数 dataUsingEncoding 把字符串转成 NSData
// HTTPBody 要的是NSData类型的数据,需要把字典转换为NSData数据
request.HTTPBody = [[NSString stringWithFormat:@"%@",dic] dataUsingEncoding:NSUTF8StringEncoding];
[NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc]init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
NSDictionary *info = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
NSLog(@"用户%@",info);
}];
</span><span style="font-size:18px;">
</span>