官方介绍

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();
    }
}

okhttp 基本介绍的更多相关文章

  1. 简单的OkHttp使用介绍

    Android系统提供了两种HTTP通信类,HttpURLConnection和HttpClient.关于HttpURLConnection和HttpClient的选择>>官方博客尽管Go ...

  2. OkHttp使用介绍

    版权声明: 欢迎转载,但请保留文章原始出处 作者:GavinCT 出处:http://www.cnblogs.com/ct2011/p/4001708.html 为什么需要一个HTTP库 Androi ...

  3. OKHttp的容易使用

    OKHttp的简单使用 一方面,最近关于OKHttp的讨论甚嚣尘上,另一方面,我最近也更新了android6.0,发现在6.0中HttpClient不能使用了,于是决定抽时间也看一下OKHttp,总结 ...

  4. OkHttp使用教程

    Android系统提供了两种HTTP通信类,HttpURLConnection和HttpClient.关于HttpURLConnection和HttpClient的选择>>官方博客尽管Go ...

  5. OkHttp使用进阶 译自OkHttp Github官方教程

    版权声明: 欢迎转载,但请保留文章原始出处 作者:GavinCT 出处:http://www.cnblogs.com/ct2011/p/3997368.html 没有使用过OkHttp的,可以先看Ok ...

  6. OkHttp使用进阶(译自OkHttp官方教程)

    没有使用过OkHttp的,可以先看OkHttp使用介绍 英文版原版地址 Recipes · square/okhttp Wiki 同步get 下载一个文件,打印他的响应头,以string形式打印响应体 ...

  7. OKHttp的简单使用

    一方面,最近关于OKHttp的讨论甚嚣尘上,另一方面,我最近也更新了android6.0,发现在6.0中HttpClient不能使用了,于是决定抽时间也看一下OKHttp,总结了一点东西,与大家分享. ...

  8. 跟我学SpringCloud | 第二十章:Spring Cloud 之 okhttp

    1. 什么是 okhttp ? okhttp 是由 square 公司开源的一个 http 客户端.在 Java 平台上,Java 标准库提供了 HttpURLConnection 类来支持 HTTP ...

  9. 从 http协议角度解析okhttp

    Okhttp 介绍 OkHttp 是 Square 公司开源的一款网络框架,封装了一个高性能的 http 请求库. 支持 spdy.http2.0.websocket 等协议 支持同步.异步请求 封装 ...

随机推荐

  1. asp.net 导入

    开发项目过程中会遇到各种各样的项目需求,我现在遇到的问题是每个部门有不同的excel文件类型,他们每个部门每个文件类型上传成功之后都会在数据库中产生表,表的列名是你excel第一行数据,其他行作为表的 ...

  2. 【RabbitMQ】 Routing

    Routing 之前的章节里我们构建了一个简单的日志系统.我们可以广播所有的日志消息给所有的接收端. 本节我们将给它添加一个新特性 - 我们将允许只订阅一个消息的子集.例如,我们只将关键的错误消息定位 ...

  3. python中对文件、文件夹的操作需要涉及到os模块和shutil模块。

    创建文件:1) os.mknod("test.txt") 创建空文件2) open("test.txt",w) 直接打开一个文件,如果文件不存在则创建文件 创建 ...

  4. eclipse 比较好的插件

    tomcat 插件 egit github 插件 subeclipse 插件 Properties Editor Properties Editor 编辑java的属性文件,并可以自动存盘为Unico ...

  5. [BZOJ - 2463] [中山市选2009] 谁能赢呢?【“博弈论”】

    题目链接:BZOJ - 2463 题目分析 这道题的题解是,由于两人都采取最优策略,所以最后一定所有格子都会被走到.(Why..表示不懂..哪位神犇可以给我讲一下QAQ) Upd:半群的神犇告诉我,并 ...

  6. Dungeon Master

    poj2251:http://poj.org/problem?id=2251 题意:给你一个三维的立方体,然后给你一个起点,和终点的坐标.然后让你求从起点到终点的最短路程.题解:该题就是求三维的最短路 ...

  7. hdu 5072 Coprime

    http://acm.hdu.edu.cn/showproblem.php?pid=5072 题意:给出 n 个互不相同的数,求满足以下条件的三元无序组的个数:要么两两互质要么两两不互质. 思路:根据 ...

  8. XFS文件系统功能解析

    XFS文件系统是作为一个日志文件系统开发,采用B-树平衡树算法来尽快地分配数据.主要的设计目的之一是支持大型文件和大型文件系统.当前,能够支持的最大文件大小是2艾字节,最大文件系统大小为8艾字节. X ...

  9. BZOJ1589: [Usaco2008 Dec]Trick or Treat on the Farm 采集糖果

    1589: [Usaco2008 Dec]Trick or Treat on the Farm 采集糖果 Time Limit: 5 Sec  Memory Limit: 64 MBSubmit: 4 ...

  10. Merge Intervals——LeetCode

    Given a collection of intervals, merge all overlapping intervals. For example,Given [1,3],[2,6],[8,1 ...