zoukankan      html  css  js  c++  java
  • okhttp 基本介绍



    官方介绍
    Overview
    HTTP is the way modern现代的 applications network. It's how we exchange data & media. Doing HTTP efficiently makes your stuff塞满 load faster and saves bandwidth节省带宽.
     
    OkHttp is an HTTP client that's efficient by default:
     
    HTTP/2 support allows all requests to the same host to share a socket.
    Connection pooling reduces request latency减少请求延迟 (if HTTP/2 isn't available).
    Transparent GZIP shrinks download sizes.
    Response caching相应缓存 avoids the network completely for repeat重复 requests.
    OkHttp perseveres when the network is troublesome: it will silently recover from common connection problems. If your service has multiple IP addresses OkHttp will attempt alternate addresses if the first connect fails. This is necessary for IPv4+IPv6 and for services hosted in redundant data centers. OkHttp initiates new connections with modern TLS features (SNI, ALPN), and falls back to TLS 1.0 if the handshake fails.
     
    Using OkHttp is easy. Its request/response API is designed with fluent builders and immutability. It supports both synchronous blocking同步阻塞 calls and async calls with callbacks.
     
    OkHttp supports Android 2.3 and above. For Java, the minimum requirement is 1.7.

    概括起来说OkHttp是一款优秀的HTTP框架,它支持get请求和post请求,支持基于Http的文件上传和下载,支持加载图片,支持下载文件透明的GZIP压缩,支持响应缓存避免重复的网络请求,支持使用连接池来降低响应延迟问题。


    Examples
    GET A URL
    This program downloads a URL and print its contents as a string. Full source.
        OkHttpClient client = new OkHttpClient();
        String run(String url) throws IOException {
            Request request = new Request.Builder().url(url).build();
            Response response = client.newCall(request).execute();
            return response.body().string();
        }  

    POST TO A SERVER
    This program posts data to a service. Full source.
        public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
        OkHttpClient client = new OkHttpClient();
        String post(String url, String json) throws IOException {
            RequestBody body = RequestBody.create(JSON, json);
            Request request = new Request.Builder().url(url).post(body).build();
            Response response = client.newCall(request).execute();
            return response.body().string();
        }  


    Download

    You'll also need Okio【https://github.com/square/okio】, which OkHttp uses for fast I/O and resizable buffers. Download the latest JAR【https://repo1.maven.org/maven2/com/squareup/okio/okio/1.11.0/okio-1.11.0.jar】.

    The source code to OkHttp, its samples, and this website is available on GitHub【https://github.com/square/okhttp】.
     
    MAVEN
    <dependency>
      <groupId>com.squareup.okhttp3</groupId>
      <artifactId>okhttp</artifactId>
      <version>3.4.2</version>
    </dependency>  

    GRADLE
    compile 'com.squareup.okhttp3:okhttp:3.4.2'  

    概要
    在学习Android的过程中,官方集成网络框架就包含了HttpUrlConnection、HttpClient、Volley,其中Volley是android开发团队在2013年Google I/O大会上推出了一个新的网络通信框架,目前Volley中部分代码仍然借助于HttpClient中部分功能,然而HttpClient在Android最新版本6.0中已经被剔除掉了,如果想要使用Volley还必须使用一个第三方的jai包org.apache.http.legacy.jar,再者Volley是针对数据量不大,但通信频繁的网络操作,而对于大数据量的网络操作,比如说下载文件等,Volley的表现就会非常糟糕。如果开发中使用HttpUrlConnection则要从头开始封装对应得操作,所以最近转向了一个第三方网络请求框架OkHttp,本文所介绍的示例都是针对OkHttp3.0库。

    OkHttp是一个 Java 的 HTTP+SPDY 客户端开发包,同时也支持 Android。需要Android 2.3以上,同时还需要一个okio包。
    注:SPDY(读作“SPeeDY”)是Google开发的基于TCP的应用层协议,用以最小化网络延迟,提升网络速度,优化用户的网络使用体验。SPDY并不是一种用于替代HTTP的协议,而是对HTTP协议的增强。新协议的功能包括数据流的多路复用、请求优先级以及HTTP报头压缩。谷歌表示,引入SPDY协议后,在实验室测试中页面加载速度比原先快64%。
    • OKHttp是Android版Http客户端。非常高效,支持SPDY、连接池、GZIP和 HTTP 缓存;
    • 默认情况下,OKHttp会自动处理常见的网络问题,像二次连接、SSL的握手问题;
    • 如果你的应用程序中集成了OKHttp,Retrofit默认会使用OKHttp处理其他网络层请求;
    • 从Android4.4开始HttpURLConnection的底层实现采用的是okHttp。

    简单使用
    OkHttp建立一个网络请求可以是异步的也可以是同步的,大体上分为三个步骤:
    1、新建一个OkHttpClient对象,可以直接new一个OkHttpClient,也可以使用建造者模式build一个,事实上new一个新的内部也是调用的build方式构建出来的。
        public OkHttpClient() {
            this(new Builder());
        }  
    2、通过Request.Builder对象新建一个Request对象,仍然使用的是建造者模式;
    3、返回执行结果,同步请求和异步请求在这里才有区别,在执行请求之前,上面两个步骤都是一样的。

    OkHttp同步请求
            OkHttpClient client = new OkHttpClient();
            Request request = new Request.Builder().url("https://www.baidu.com/").build();
            try {
                Response response = client.newCall(request).execute();
                if (response.isSuccessful()) {
                    Log.i("bqt", response.body().string());
                }
            } catch (IOException e) {
                e.printStackTrace();
            }  
    这里建立的默认请求采用的是get方式请求的,源码如下:
        public Builder() {
            this.method = "GET";
            this.headers = new Headers.Builder();
        }

    OkHttp异步请求
            OkHttpClient client = new OkHttpClient();
            Request request = new Request.Builder().url("https://www.baidu.com/").build();
            client.newCall(request).enqueue(new Callback() {//注意:这里的回调函数是在【子线程】中执行的
                @Override
                public void onFailure(Call call, IOException e) {
                }
                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    Log.i("bqt", response.body().string());
                }
            });  
    我们一般会借助于Handler消息机制来处理回调

    post请求
    这里所讲的post请求,仅仅限制在表单提交中,也就是content-type为” application/x-www-form-urlencoded”的请求,其余的方式如文件上传下次再做介绍。对于post方式提交表单,OkHttp已经封装好了相应的类FormBody来设置表单的参数,示例代码如下:
            OkHttpClient client = new OkHttpClient();
            RequestBody formBody = new FormBody.Builder().add("name""木子").add("pwd""123456").build();
            Request request = new Request.Builder().url("uri").post(formBody).build();
            client.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                }
                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    Log.i("bqt", response.body().string());
                }
            });  

    示例代码
    public class MainActivity extends Activity {
        public TextView textView;
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            textView = new TextView(this);
            textView.setText("包青天");
            setContentView(textView);
            new Thread(new Runnable() {
                @Override
                public void run() {
                    Request request = new Request.Builder().url("https://www.baidu.com/").build();
                    new OkHttpClient().newCall(request).enqueue(new Callback() {//注意:这里的回调函数是在【子线程】中执行的
                                @Override
                                public void onFailure(Call call, IOException e) {
                                }
                                @Override
                                public void onResponse(Call call, Response response) throws IOException {
                                    Log.i("bqt", response.body().string());
                                    //textView.setText(response.body().string());
                                }
                            });
                }
            }).start();
        }
    }





  • 相关阅读:
    Yii中CreateUrl的使用总结
    scite配置文件及常用设置
    smarty中判断数组是否为空的方法
    Notepad++添加插件Funtion List 支持PHP
    类的例子1
    class的使用
    lambda 的使用汇总
    作用域
    模块的整理汇总
    函数使用的健壮性
  • 原文地址:https://www.cnblogs.com/baiqiantao/p/2ed585a38ed4bce924341b01e681397f.html
Copyright © 2011-2022 走看看