OKHttp是一款高效的HTTP客户端,支持连接同一地址的链接共享同一个socket,通过连接池来减小响应延迟,还有透明的GZIP压缩,请求缓存等优势。(GitHub页:https://github.com/square/okhttp)
Android为我们提供了两种HTTP交互的方式:HttpURLConnection 和 Apache HTTP Client,虽然两者都支持HTTPS,流的上传和下载,配置超时,IPv6和连接池,已足够满足我们各种HTTP请求的需求。但更高效的使用HTTP 可以让您的应用运行更快、更节省流量。而OkHttp库就是为此而生。
OkHttp是一个高效的HTTP库:
如果您的服务器配置了多个IP地址,当第一个IP连接失败的时候,OkHttp会自动尝试下一个IP。OkHttp还处理了代理服务器问题和SSL握手失败问题。
使用 OkHttp 无需重写您程序中的网络代码。OkHttp实现了几乎和java.net.HttpURLConnection一样的API。如果您用了 Apache HttpClient,则OkHttp也提供了一个对应的okhttp-apache 模块。
引入
可以通过下载jar包直接导入工程地址
或者通过构建的方式导入
MAVEN:
<dependency> <groupId>com.squareup.okhttp</groupId> <artifactId>okhttp</artifactId> <version>2.4.0</version> </dependency>
GRADLE:
compile 'com.squareup.okhttp:okhttp:2.4.0'用法
package com.jackchan.test.okhttptest; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.util.Log; import com.squareup.okhttp.Cache; import com.squareup.okhttp.Callback; import com.squareup.okhttp.OkHttpClient; import com.squareup.okhttp.Request; import com.squareup.okhttp.Response; import java.io.File; import java.io.IOException; public class TestActivity extends ActionBarActivity { private final static String TAG = "TestActivity"; private final OkHttpClient client = new OkHttpClient(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_test); new Thread(new Runnable() { @Override public void run() { try { execute(); } catch (Exception e) { e.printStackTrace(); } } }).start(); } public void execute() throws Exception { Request request = new Request.Builder() .url("http://publicobject.com/helloworld.txt") .build(); Response response = client.newCall(request).execute(); if(response.isSuccessful()){ System.out.println(response.code()); System.out.println(response.body().string()); } } }我们通过Request.Builder传入url,然后直接execute执行得到Response,通过Response可以得到code,message等信息。
private void enqueue(){ Request request = new Request.Builder() .url("http://publicobject.com/helloworld.txt") .build(); client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Request request, IOException e) { } @Override public void onResponse(Response response) throws IOException { //NOT UI Thread if(response.isSuccessful()){ System.out.println(response.code()); System.out.println(response.body().string()); } } }); }就是在同步的基础上讲execute改成enqueue,并且传入回调接口,但接口回调回来的代码是在非UI线程的,因此如果有更新UI的操作记得用Handler或者其他方式。
Request request = new Request.Builder() .url("https://api.github.com/repos/square/okhttp/issues") .header("User-Agent", "OkHttp Headers.java") .addHeader("Accept", "application/json; q=0.5") .addHeader("Accept", "application/vnd.github.v3+json") .build();传入POST参数
RequestBody formBody = new FormEncodingBuilder() .add("platform", "android") .add("name", "bug") .add("subject", "XXXXXXXXXXXXXXX") .build(); Request request = new Request.Builder() .url(url) .post(body) .build();可以看出来,传入header或者post参数都是传到Request里面,因此最后的调用方式也和GET方式一样
Response response = client.newCall(request).execute(); if (response.isSuccessful()) { return response.body().string(); } else { throw new IOException("Unexpected code " + response); }这个代码是同步网络请求,异步就改成enqueue就行了。
package com.jackchan.test.okhttptest; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.util.Log; import com.squareup.okhttp.Cache; import com.squareup.okhttp.CacheControl; import com.squareup.okhttp.Call; import com.squareup.okhttp.Callback; import com.squareup.okhttp.OkHttpClient; import com.squareup.okhttp.Request; import com.squareup.okhttp.Response; import java.io.File; import java.io.IOException; public class TestActivity extends ActionBarActivity { private final static String TAG = "TestActivity"; private final OkHttpClient client = new OkHttpClient(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_test); File sdcache = getExternalCacheDir(); int cacheSize = 10 * 1024 * 1024; // 10 MiB client.setCache(new Cache(sdcache.getAbsoluteFile(), cacheSize)); new Thread(new Runnable() { @Override public void run() { try { execute(); } catch (Exception e) { e.printStackTrace(); } } }).start(); } public void execute() throws Exception { Request request = new Request.Builder() .url("http://publicobject.com/helloworld.txt") .build(); Response response1 = client.newCall(request).execute(); if (!response1.isSuccessful()) throw new IOException("Unexpected code " + response1); String response1Body = response1.body().string(); System.out.println("Response 1 response: " + response1); System.out.println("Response 1 cache response: " + response1.cacheResponse()); System.out.println("Response 1 network response: " + response1.networkResponse()); Response response2 = client.newCall(request).execute(); if (!response2.isSuccessful()) throw new IOException("Unexpected code " + response2); String response2Body = response2.body().string(); System.out.println("Response 2 response: " + response2); System.out.println("Response 2 cache response: " + response2.cacheResponse()); System.out.println("Response 2 network response: " + response2.networkResponse()); System.out.println("Response 2 equals Response 1? " + response1Body.equals(response2Body)); } }okhttpclient有点像Application的概念,统筹着整个okhttp的大功能,通过它设置缓存目录,我们执行上面的代码,得到的结果如下
public void execute() throws Exception { Request request = new Request.Builder() .url("http://publicobject.com/helloworld.txt") .build(); Response response1 = client.newCall(request).execute(); if (!response1.isSuccessful()) throw new IOException("Unexpected code " + response1); String response1Body = response1.body().string(); System.out.println("Response 1 response: " + response1); System.out.println("Response 1 cache response: " + response1.cacheResponse()); System.out.println("Response 1 network response: " + response1.networkResponse()); request = request.newBuilder().cacheControl(CacheControl.FORCE_NETWORK).build(); Response response2 = client.newCall(request).execute(); if (!response2.isSuccessful()) throw new IOException("Unexpected code " + response2); String response2Body = response2.body().string(); System.out.println("Response 2 response: " + response2); System.out.println("Response 2 cache response: " + response2.cacheResponse()); System.out.println("Response 2 network response: " + response2.networkResponse()); System.out.println("Response 2 equals Response 1? " + response1Body.equals(response2Body)); }上面的代码中
request = request.newBuilder().cacheControl(CacheControl.FORCE_NETWORK).build();我们看看运行结果
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_test); File sdcache = getExternalCacheDir(); int cacheSize = 10 * 1024 * 1024; // 10 MiB //client.setCache(new Cache(sdcache.getAbsoluteFile(), cacheSize)); new Thread(new Runnable() { @Override public void run() { try { execute(); } catch (Exception e) { e.printStackTrace(); System.out.println(e.getMessage().toString()); } } }).start(); } public void execute() throws Exception { Request request = new Request.Builder() .url("http://publicobject.com/helloworld.txt") .build(); Response response1 = client.newCall(request).execute(); if (!response1.isSuccessful()) throw new IOException("Unexpected code " + response1); String response1Body = response1.body().string(); System.out.println("Response 1 response: " + response1); System.out.println("Response 1 cache response: " + response1.cacheResponse()); System.out.println("Response 1 network response: " + response1.networkResponse()); request = request.newBuilder().cacheControl(CacheControl.FORCE_CACHE).build(); Response response2 = client.newCall(request).execute(); if (!response2.isSuccessful()) throw new IOException("Unexpected code " + response2); String response2Body = response2.body().string(); System.out.println("Response 2 response: " + response2); System.out.println("Response 2 cache response: " + response2.cacheResponse()); System.out.println("Response 2 network response: " + response2.networkResponse()); System.out.println("Response 2 equals Response 1? " + response1Body.equals(response2Body)); }取消操作
public void canceltest() throws Exception { Request request = new Request.Builder() .url("http://httpbin.org/delay/2") // This URL is served with a 2 second delay. .build(); final long startNanos = System.nanoTime(); final Call call = client.newCall(request); // Schedule a job to cancel the call in 1 second. executor.schedule(new Runnable() { @Override public void run() { System.out.printf("%.2f Canceling call.%n", (System.nanoTime() - startNanos) / 1e9f); call.cancel(); System.out.printf("%.2f Canceled call.%n", (System.nanoTime() - startNanos) / 1e9f); } }, 1, TimeUnit.SECONDS); try { System.out.printf("%.2f Executing call.%n", (System.nanoTime() - startNanos) / 1e9f); Response response = call.execute(); System.out.printf("call is cancel:" + call.isCanceled() + "%n"); System.out.printf("%.2f Call was expected to fail, but completed: %s%n", (System.nanoTime() - startNanos) / 1e9f, response); } catch (IOException e) { System.out.printf("%.2f Call failed as expected: %s%n", (System.nanoTime() - startNanos) / 1e9f, e); } }成功取消
本文向大家介绍Android OkHttp基本使用详解,包括了Android OkHttp基本使用详解的使用技巧和注意事项,需要的朋友参考一下 Android系统提供了两种HTTP通信类,HttpURLConnection和HttpClient。 尽管Google在大部分安卓版本中推荐使用HttpURLConnection,但是这个类相比HttpClient实在是太难用,太弱爆了。 OkHttp是
问题内容: 我正在尝试使用OkHttp,但是它一直崩溃。有人可以快速浏览一下,看看是否知道发生了什么事。谢谢。 日志猫: 这是我尝试使用的代码示例。它来自在线教程(teamtreehouse.com)Java代码: 问题答案: OkHttp需要Okio,OkHttp可以使用Okio来实现快速I / O和可调整大小的缓冲区。您可以在此处下载Okio(最新的JAR)。 要么 Android gradl
本文向大家介绍C#使用Redis的基本操作,包括了C#使用Redis的基本操作的使用技巧和注意事项,需要的朋友参考一下 一,引入dll 1.ServiceStack.Common.dll 2.ServiceStack.Interfaces.dll 3.ServiceStack.Redis.dll 4.ServiceStack.Text.dll 二,修改配置文件 在你的配置文件中
在我更新sdk并在我的项目中使用API23后,我发现有一些错误,因为找不到相关的包,然后我找到它,知道API23已经删除了apache http包。 那么现在什么是旧的apache http包的替代品,换句话说,如何在Android API23中处理volley以避免错误。 我去过Volley的谷歌源搜索新版本,但似乎没有解决方案。
使用quare https://github.com/Square/OkHttp的OkHttp,我如何: 检索从服务器返回的cookie 为即将到来的请求存储cookie 在后续请求中使用存储的cookie 更新后续请求返回的cookie 理想情况下,cookie将随每个请求自动存储、重新发送和更新。
我正在为一个新项目使用OkHttp库,它的易用性给我留下了深刻的印象。我现在需要使用基本身份验证。不幸的是,缺少可用的示例代码。我正在寻找一个示例,说明在遇到HTTP 401头时如何将用户名/密码凭据传递给OkAuthenticator。我看到了这个答案: 改装带有基本HTTP身份验证的POST请求:“无法重试流式HTTP正文” 但这并没有让我走得太远。OkHttp github repo上的示例
本文向大家介绍MongoDB使用指南--基本操作,包括了MongoDB使用指南--基本操作的使用技巧和注意事项,需要的朋友参考一下 读取 db.collection.find() users是collection名字,从users中查找; age是query criteria,筛选结果,代表查找name字段的值比18大的; name是projection,筛选列(1代表存在, 0代表不存在),代表
5.1 Excel 基础操作 Range相关 Range 属性的一些 A1 样式引用 Range("A1") ' 单元格 A1 Range("A1:B5") ' 从单元格 A1 到单元格 B5 的区域 Range("C5:D9, G9:H16") ' 多块选定区域 ' 选中不关联的单元格,cells(2, 3)返回结果为:B3 Union(Range("