iOS 开发之网络请求

iOS 开发之网络请求


     一、http: 超文本传输协议( HyperText Transfer Protocol )

     所有的www文件都必须遵守这个标准

     http是用于www(万维网)浏览传输数据的一个协议

     http:// 服务器地址 资源的位置

     IP协议对应于网络层 TCP协议对应于传输层,HTTP协议对应于应用层

     

     二、http协议的作用:

     1、规定客服端和服务器之间的数据传输格式

     2、让客服端和服务器能有效的进行数据沟通

     

     三、使用 http 的好处:

     简单快速 灵活 允许传输任意类型的数据 限制每次连接只处理一个请求节省传输时间

     

     四、HTTP的通信过程:

     1、请求:客户端向服务器索要数据

     2、响应:服务器返回客户端相应的数据

     


     五、HTTP 主要请求方法 get psot

     

     get: 会把请求的内容 拼接到 连接地址里面(数据请求的时候 默认的是get方式)

     get:特征

      1、浏览器和服务器对URL长度有限制,因此在URL后面附带的参数是有限的,通常不超过1KB

      2、会把请求的数据暴露在接口里面


     post: 参数全部放在请求体中 这样就保证了数据的安全 没有具体的长度限制(唯一的限制就是 服务器的承受能力)


     六、选择GETPOST的建议:

     1、如果需要传递大量数据,比如文件上传,只能用 post 请求

     2GET的安全性比post要差一些,如果包含机密信息,建议用post

     3、如果仅仅是索取数据(数据查询),建议使用get

     4、如果是增加、修改、删除数据的时候,建议使用post

     

     七、URL: Uniform Resource Locator (统一资源定位符)

     通过1URL,能找到互联网上唯一的1个资源


     八、网络请求: 同步请求  异步请求

      同步请求: 等所有操作 完全执行完毕 才会 继续执行

      同步请求的弊端: 会遇到 假死 的情况 ( 只要 请求 的操作 没有执行完毕 就不会再 去响应 任何时间(在统一线程) )

      异步请求: 在程序运行的时候 会利用空闲的时间 去执行里面的操作 不会影响 到同一线程里面 的其他操作

     

具体代码如下:

#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController

- (void)viewDidLoad{
    [super viewDidLoad];

//    [ self loadData1 ] ;
//    [ self loadData2 ] ;
//    [ self loadData3 ] ;
//    [ self loadData4 ] ;
//    [ self loadData5 ] ;
    [ self loadData6 ] ;
}


// 通过URL获得到 URL 转成 NSURL
 - (void)loadData1
{
//    把 字符串 转成 NSURL
    NSURL *url = [ NSURL URLWithString:@"http://www.gyu.cn" ];
    
    NSString *content = [ NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil ];
    
    NSLog(@"%@",content); 
}


 - (void)loadData2
{
    NSURL *url = [ NSURL URLWithString:@"http://preview.quanjing.com/is_rm001/is0997q92.jpg" ];
    NSData *data = [ NSData dataWithContentsOfURL:url ];
    
    UIImageView *image = [[ UIImageView alloc ]initWithFrame:self.view.frame];
    image.contentMode = UIViewContentModeScaleAspectFit;
    image.image=[UIImage imageWithData:data];
    [self.view addSubview:image];
}


// 同步请求
 - (void)loadData3
{
    NSURL *url = [ NSURL URLWithString:@"http://preview.quanjing.com/is_rm001/is0997q92.jpg" ];
    
//    实例化 请求对象  里面 携带 着 请求地址
    NSURLRequest *request = [ NSURLRequest requestWithURL:url ];
    
//    data 服务响应(返回)给咱们的数据
//    NSURLConnection 发送请求的类
    NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    
    UIImageView *image = [[ UIImageView alloc ]initWithFrame:self.view.frame];
    image.contentMode = UIViewContentModeScaleAspectFit;
    image.image=[UIImage imageWithData:data];
    [self.view addSubview:image];
}

// 异步请求
 - (void)loadData4
{
    NSURL *url = [ NSURL URLWithString:@"http://preview.quanjing.com/is_rm001/is0997q92.jpg" ];
    
    //    实例化 请求对象  里面 携带 着 请求地址
    NSURLRequest *request = [ NSURLRequest requestWithURL:url ];
    
    UIImageView *image = [[ UIImageView alloc ]initWithFrame:self.view.frame];
    image.contentMode = UIViewContentModeScaleAspectFit;
    [self.view addSubview:image];
    
    
//    需要 通过 连接 异步发送 请求
//    线程
    NSOperationQueue *queue = [[ NSOperationQueue alloc ]init];
    
//    发送 一个异步请求 在 queue 这个线程里面去执行
       [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
           
//     response 服务器 回应的 内容 (回应的状态的code 以及 error)
//     data 是回应给 客户端 需要的数据
          
//       NSLog(@"%@",response);
        image.image=[UIImage imageWithData:data];
           
       }];
}


// get  把传输的数据 放在链接地址里
 - (void)loadData5
{
   NSString *interfaceString = @"http://apis.baidu.com/showapi_open_bus/mobile/find";
   NSString *requestContentString = @"num=18984355035";
    
   NSString *urlString = [ NSString stringWithFormat:@"%@?%@",interfaceString,requestContentString ];
   
//    把链接地址字符串 转成 NSUTF8StringEncoding
    NSURL *url = [ NSURL URLWithString:[ urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding ] ];
    
//   可变请求 可以添加 请求方式 以及请求 的 请求头 或者 更多
//   timeoutInterval 请求所需的时间 超过 时间 不再发送这个请求
//   cachePolicy 缓存内容的方式
    NSMutableURLRequest *request = [ NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10 ];
//    指定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);
        NSLog(@"%@ %@",info[@"showapi_res_body"][@"city"] ,info[@"showapi_res_body"][@"name"] );
        
    }];
    
}


// post
 - (void)loadData6
{
    NSURL *url= [NSURL URLWithString: @"http://www.weihuok.com/customer2/GetService"];
    
//    请求的参数
//   PlatformType 设备类型   3 表示ios设备
    NSDictionary *dic = @{@"PlatformType":@"3"};
    NSMutableURLRequest *request = [ NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10 ];
    
//    设置HTTP请求的方式
    request.HTTPMethod = @"POST";
    
//    设置 请求的参数
//    dataUsingEncoding  把字符串 转成 Data 类型
//    HTTPBody 要的是 data 数据类型
    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);
    }];
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值