okhttp 基本介绍
官方介绍
OverviewHTTP 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压缩,支持响应缓存避免重复的网络请求,支持使用连接池来降低响应延迟问题。ExamplesGET A URLThis 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 SERVERThis 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();}DownloadYou'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>GRADLEcompile '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() {//注意:这里的回调函数是在【子线程】中执行的@Overridepublic void onFailure(Call call, IOException e) {}@Overridepublic 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() {@Overridepublic void onFailure(Call call, IOException e) {}@Overridepublic 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() {@Overridepublic void run() {Request request = new Request.Builder().url("https://www.baidu.com/").build();new OkHttpClient().newCall(request).enqueue(new Callback() {//注意:这里的回调函数是在【子线程】中执行的@Overridepublic void onFailure(Call call, IOException e) {}@Overridepublic void onResponse(Call call, Response response) throws IOException {Log.i("bqt", response.body().string());//textView.setText(response.body().string());}});}}).start();}}
okhttp 基本介绍的更多相关文章
- 简单的OkHttp使用介绍
Android系统提供了两种HTTP通信类,HttpURLConnection和HttpClient.关于HttpURLConnection和HttpClient的选择>>官方博客尽管Go ...
- OkHttp使用介绍
版权声明: 欢迎转载,但请保留文章原始出处 作者:GavinCT 出处:http://www.cnblogs.com/ct2011/p/4001708.html 为什么需要一个HTTP库 Androi ...
- OKHttp的容易使用
OKHttp的简单使用 一方面,最近关于OKHttp的讨论甚嚣尘上,另一方面,我最近也更新了android6.0,发现在6.0中HttpClient不能使用了,于是决定抽时间也看一下OKHttp,总结 ...
- OkHttp使用教程
Android系统提供了两种HTTP通信类,HttpURLConnection和HttpClient.关于HttpURLConnection和HttpClient的选择>>官方博客尽管Go ...
- OkHttp使用进阶 译自OkHttp Github官方教程
版权声明: 欢迎转载,但请保留文章原始出处 作者:GavinCT 出处:http://www.cnblogs.com/ct2011/p/3997368.html 没有使用过OkHttp的,可以先看Ok ...
- OkHttp使用进阶(译自OkHttp官方教程)
没有使用过OkHttp的,可以先看OkHttp使用介绍 英文版原版地址 Recipes · square/okhttp Wiki 同步get 下载一个文件,打印他的响应头,以string形式打印响应体 ...
- OKHttp的简单使用
一方面,最近关于OKHttp的讨论甚嚣尘上,另一方面,我最近也更新了android6.0,发现在6.0中HttpClient不能使用了,于是决定抽时间也看一下OKHttp,总结了一点东西,与大家分享. ...
- 跟我学SpringCloud | 第二十章:Spring Cloud 之 okhttp
1. 什么是 okhttp ? okhttp 是由 square 公司开源的一个 http 客户端.在 Java 平台上,Java 标准库提供了 HttpURLConnection 类来支持 HTTP ...
- 从 http协议角度解析okhttp
Okhttp 介绍 OkHttp 是 Square 公司开源的一款网络框架,封装了一个高性能的 http 请求库. 支持 spdy.http2.0.websocket 等协议 支持同步.异步请求 封装 ...
随机推荐
- TatukGIS - GisDefs - DateTimeToXMLString 函数
函数名称 DateTimeToXMLString 所在单元 GisDefs 函数原型 function DateTimeToXMLString(_dtm: TDateTime; ...
- centos挂存储
#看硬盘有木 fdisk -l #格式化 parted /dev/sdb mklabel gpt print quit #如果多个分区执行 如果不要么 #mkpart primary 0 4.5T ...
- arm-none-eabi-gcc install
Zephyr除了官方的编译工具,还有第三方工具 arm-none-eabi-gcc . This PPA is an alternative to toolchain released at http ...
- sql 学习之 group by 及 聚合函数
1.在使用 GROUP BY 子句时,Select列表中的所有列必须是聚合列(SUM,MIN/MAX,AVG等)或是GROUP BY 子句中包括的列.同样,如果在SELECT 列表中使用聚合列,SEL ...
- Github博客地址
欢迎访问我的Github博客: J.R.Smith_blog
- 工作总结:将电脑中的ARP缓存清空黑屏命令
ARP -d 将电脑中的ARP缓存清空ARP-a 查看arp缓存arp-s ip与mac绑定
- hibernate spring sturts2配置
<?xml version='1.0' encoding='utf-8'?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hi ...
- BZOJ 3575 道路堵塞
Description A国有N座城市,依次标为1到N.同时,在这N座城市间有M条单向道路,每条道路的长度是一个正整数.现在,A国交通部指定了一条从城市1到城市N的路径,并且保证这条路径的长度是所有从 ...
- 舍伍德(Sherwood)算法学习笔记
一.概念引入 设A是一个确定性算法,当它的输入实例为x时所需的计算时间记为tA(x).设Xn是算法A的输入规模为n的实例的全体,则当问题的输入规模为n时,算法A所需的平均时间为.这显然不能排除存在x∈ ...
- Highways
poj1751:http://poj.org/problem?id=1751 题意:给你n个城市,每个城市的坐标给你,然后为了是每个城市都连通,需要在已经建了一些街道额基础上,再次建一些街道使其连通, ...