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 等协议 支持同步.异步请求 封装 ...
随机推荐
- openerp import l field size limit
modify the file addons/base_import/models.py add the following line at the very begining of the _con ...
- C++实现base64编码
将昨天的php代码改造成C++ /*base_64.h文件*/ #ifndef BASE_64_H #define BASE_64_H /** * Base64 编码/解码 * @author lir ...
- nginx下搭建fastcgi的开发环境
在上一章最简单理解CGI,FastCGI,WSGI 我们将fastcgi规范类比HTTP.下面我们通过一个案例更加明白fastcgi 我们使用的是 nginx作为前端 代理,我们包装了gevent_ ...
- Building a Space Station
poj2031:http://poj.org/problem?id=2031 题意:就是给出三维坐标系上的一些球的球心坐标和其半径,搭建通路,使得他们能够相互连通.如果两个球有重叠的部分则算为已连通, ...
- Unity 小地图制作插件NJG MiniMap的简单使用
unity版本:4.5.1 NJG MiniMap版本:1.5 参考链接:http://blog.csdn.net/wuming22222/article/details/37526659,作者:CS ...
- Squares(哈希)
Time Limit: 3500MS Memory Limit: 65536K Total Submissions: 14328 Accepted: 5393 Description A sq ...
- -_-#【jQuery】data
.data() <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <t ...
- 数据结构(虚树,动态规划):HNOI 2014 世界树
Hnoi2014 世界树 Description 世界树是一棵无比巨大的树,它伸出的枝干构成了整个世界.在这里,生存着各种各样的种族和生灵,他们共同信奉着绝对公正公平的女神艾莉森,在他们的信条里,公平 ...
- c++学习(1)
c++学习(1) 1.const C VS C++: 在c语言中const是一个只读变量(ReadOnly Varible),在c++中const只是代表常量(Constant). 例: const ...
- 动态规划——F 最大矩阵和
Given a two-dimensional array of positive and negative integers, a sub-rectangle is any contiguous s ...