zoukankan      html  css  js  c++  java
  • IOS NSURLRequest(http请求)讲解 ---------赎罪之路

    前言

         很久没有写过博客了,今天终于可以抽空写。公司的项目从2016年03月15日(我第二份工作任职)开始,辛苦了3个多月终于接近尾声了,在这当中我学了非常多东西,为了遗忘我就写个博客来记录下,以防止忘记。

    正文  

         今天要讲的主角是NSURLRequest。这里我先采用apple 官方文档解释

    NSURLRequest objects represent a URL load request in a manner independent of protocol and URL scheme,

    NSURLRequest encapsulates two basic data elements of a load request: the URL to load, and the policy to use when consulting the URL content cache made available by the implementation.

    NSURLRequest is designed to be extended to support additional protocols by adding categories that provide accessor methods for your own protocol-specific properties. Those methods can get and set the actual values by calling the NSURLProtocol methods propertyForKey:inRequest: and setProperty:forKey:inRequest:.

    以上引用苹果官方解释,大概就是NSURLRequest 是一个独立的独立加载请求的协议和解决方案,它封装了 load URL 和 the policy,当你发送了网络请求时候可以使用缓存,你可以通过它 propertyForKey:inRequest: 和 setProperty:forKey:inRequest:.这两个方法添加你的协议,英语笔记差,翻译不正确请指出。

     

       其实苹果说了这多,说白就是这个是可以让你发送网络请求,你可以为这个类添加缓存,使得相同的URL不必在进行一次网络请求,缓存到后面我们慢慢再谈论,因为今天的主角是NSURLRequest。

     

    例子一

        //1 需要请求的URL

        NSString *imageUrl = @"https://ss0.bdstatic.com/94oJfD_bAAcT8t7mm9GUKT-xh_/timg?image&quality=100&size=b4000_4000&sec=1467208812&di=3b6365a0a40959e9b1f9432372bc1ee3&src=http://img5.duitang.com/uploads/item/201208/13/20120813000951_iF2K4.thumb.700_0.jpeg";

        

        //2 NSString 封装成 NSURL

        NSURL *url = [NSURL URLWithString:imageUrl];

        

        //3 定义NSURLRequest 对象

        NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];

        

        //4 发送请求

        

        [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {

            

            if(!connectionError){

                

                NSLog(@"加载成功");

                

                dispatch_async(dispatch_get_main_queue(), ^{

                    

                    //加载Image

                    

                    UIImage *image = [UIImage imageWithData:data];

                    

                    //显示到UIImageView

                    self.imageView.image = image;

                });

                

            }

            else

                NSLog(@"加载失败");

        }];

    第一个例子非常简单,主要是引入门。大家可能会奇怪,为什么我没有设置请求的类型(get 或者 post),因为NSURLReqest 默认是GET请求,所以我才没有设置而没有提示错误。

    例子二(post请求)

        // 1 需要请求的URL String
        NSString *urlString = @"http://fmonline.server.kugou.net:8080/get_online";
        
        // 2 封装成NSURL
        NSURL *url          = [NSURL URLWithString:urlString];
        
        // 3 定义NSURLRquest
        NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];//注意这个是mutable,说明这个是可变的
        
        // 4设置对应的属性
        
        // 设置请求类型
        request.HTTPMethod   = @"post";//默认是 get

          //添加url

            request.URL          = url;

        //设置body内容
        NSString *bodyString = @"¼r¹}9:";
        NSData   *bodyData   = [bodyString dataUsingEncoding:NSUTF8StringEncoding];
        request.HTTPBody     = bodyData;
        
        [NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
            
        }];
    

       post请求一般都是采用NSMutableURLRequest 进行网络请求,因为post请求一般包括 body 参数 或者 head。

    简单的两个例子初步学习IOS 如何进行网络请求

    重点

    在ios 9 即(xcode7)需要在info.plist

    <key>NSAllowsArbitraryLoads</key>
    <true/>
    <key>NSAppTransportSecurity</key>
    <true/>

    因为 iOS 9 就停用了http请求,默认采用https,但是目前没有多少公司采用了https请求,因为要多支出费用。

    结言

    NSURLRequest 目前暂时先讲到这里,下次我们来讲NSURLConnect。

    demo 下载地址 https://github.com/YeYanHong/NSURLReqest-Demo

  • 相关阅读:
    编写一个程序的步骤
    vue实现瀑布流
    Vue 解决动态生成列表点击事件无效的问题
    筛选分类列表展示
    php实现类似慕课网,php中文网的分类功能
    在一个页面修改数据,并且ajax刷新数据列表的数据实现。
    记账小程序系统简单规划
    茶叶项目---产品的规格添加
    茶叶商城开发
    后端图片上传
  • 原文地址:https://www.cnblogs.com/HeiNeiKu/p/5628498.html
Copyright © 2011-2022 走看看