以下是一些简单关于网络的常识
http: 超文本传输协议(HyperText Transfer Protocol)
http 规定客服端和服务器之间的传输格式
为什么选择使用http
1.简单快速 http协议简单 服务器程序规模小 所以通信快速
2.灵活 可以传输任意数据类型
3.http 是非持续链接 限制每次只处理一个请求 服务器响应后马上断开链接 这样可以节省时间
http 通信过程
1.请求 客服端
2.响应 服务器
*****
http的常用请求方式:get post
get 会将请求的内容拼接到连接地址里面(数据请求的时候 默认get请求)
get 特征
1.浏览器和服务器对URL的长度有限制 因此在URL后面附带的参数是有限制的 通常不超过1KB
2.它会把请求的数据暴露在接口里面
post 参数全部放在请求体中 这样就保证了数据的基本安全并且请求体没有长度限制(唯一限制就是服务器的承受能力)
选择get和post的建议
1.如果要传输大量数据 譬如文件上传 只能用post
2.get的安全比post差一些 如果包含机密/敏感信息 建议用post
3.如果是增长、修改、删除数据、建议用post
URL:uniform resource locator(统一资源定位符)
通过1个URL、能找到互联网唯一的一个资源
如果是iOS9需要取消对网络的限制,在plist里添加以下代码,适配一下
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
下面是一个简单的get请求实例:
// get 把传输的数据 放在连接地址里面
- (void)loadData_5
{
NSString *interfaceString = @"http://apis.baidu.com/showapi_open_bus/mobile/find";
NSString *requestContentString = @"num=13370116152";
NSString *urlString = [NSString stringWithFormat:@"%@ ? %@",interfaceString,requestContentString];
// 把链接地址字符串 转成 NSUTF8StringEncoding
NSURL *url = [NSURL URLWithString:[urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
// 可变请求可以添加请求方式 以及请求的请求头或者更多 (NSTimeInterval) 允许请求的时间 超过时间就不在发送请求
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:5];
// 指定http的请求方式
request.HTTPMethod = @"GET";
NSString *apiKey = @"e7f5ac9e7c42a6c8cb125ee1d7e8779e";
// 把apikey 发送给服务器指定的请求头位置 forHTTPHeaderField 需要的Key 是服务器指定的Key
[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[@"showapi_res_body"][@"city"],info[@"showapi_res_body"][@"name"]);
}];
}
下面是post请求的一个实例:
// post请求下来的是一个 HTTPBody 需要JSON解析为我们需要的NSData类型
- (void)loadData_6
{
NSURL *url = [NSURL URLWithString:@"http://www.weihuok.com/customer2/GetService"];
// 请求参数 PlatformType 平台类型
NSDictionary *dic = @{@"PlatformType":@"3"};
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:5];
request.HTTPMethod = @"POST";
// dataUsingEncoding:NSUTF8StringEncoding 将字符串直接转化成 NSData 因为 HTTPBody 需要的是 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);
}];
}