Android中okhttp3使用詳解
一、引入包
在項(xiàng)目module下的build.gradle添加okhttp3依賴
compile 'com.squareup.okhttp3:okhttp:3.3.1'
二、基本使用
1、okhttp3 Get 方法
1.1 、okhttp3 同步 Get方法
/**
* 同步Get方法
*/
private void okHttp_synchronousGet() {
new Thread(new Runnable() {
@Override
public void run() {
try {
String url = "https://api.github.com/";
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url(url).build();
okhttp3.Response response = client.newCall(request).execute();
if (response.isSuccessful()) {
Log.i(TAG, response.body().string());
} else {
Log.i(TAG, "okHttp is request error");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
Request是okhttp3 的請求對象,Response是okhttp3中的響應(yīng)。通過response.isSuccessful()判斷請求是否成功。
@Contract(pure=true) public boolean isSuccessful() Returns true if the code is in [200..300), which means the request was successfully received, understood, and accepted.
獲取返回的數(shù)據(jù),可通過response.body().string()獲取,默認(rèn)返回的是utf-8格式;string()適用于獲取小數(shù)據(jù)信息,如果返回的數(shù)據(jù)超過1M,建議使用stream()獲取返回的數(shù)據(jù),因?yàn)閟tring() 方法會(huì)將整個(gè)文檔加載到內(nèi)存中。
@NotNull
public final java.lang.String string()
throws java.io.IOException
Returns the response as a string decoded with the charset of the Content-Type header. If that header is either absent or lacks a charset, this will attempt to decode the response body as UTF-8.
Throws:
java.io.IOException
當(dāng)然也可以獲取流輸出形式;
public final java.io.InputStream byteStream()
1.2 、okhttp3 異步 Get方法
有時(shí)候需要下載一份文件(比如網(wǎng)絡(luò)圖片),如果文件比較大,整個(gè)下載會(huì)比較耗時(shí),通常我們會(huì)將耗時(shí)任務(wù)放到工作線程中,而使用okhttp3異步方法,不需要我們開啟工作線程執(zhí)行網(wǎng)絡(luò)請求,返回的結(jié)果也在工作線程中;
/**
* 異步 Get方法
*/
private void okHttp_asynchronousGet(){
try {
Log.i(TAG,"main thread id is "+Thread.currentThread().getId());
String url = "https://api.github.com/";
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url(url).build();
client.newCall(request).enqueue(new okhttp3.Callback() {
@Override
public void onFailure(okhttp3.Call call, IOException e) {
}
@Override
public void onResponse(okhttp3.Call call, okhttp3.Response response) throws IOException {
// 注:該回調(diào)是子線程,非主線程
Log.i(TAG,"callback thread id is "+Thread.currentThread().getId());
Log.i(TAG,response.body().string());
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
注:Android 4.0 之后,要求網(wǎng)絡(luò)請求必須在工作線程中運(yùn)行,不再允許在主線程中運(yùn)行。因此,如果使用 okhttp3 的同步Get方法,需要新起工作線程調(diào)用。
1.3 、添加請求頭
okhttp3添加請求頭,需要在Request.Builder()使用.header(String key,String value)或者.addHeader(String key,String value);
使用.header(String key,String value),如果key已經(jīng)存在,將會(huì)移除該key對應(yīng)的value,然后將新value添加進(jìn)來,即替換掉原來的value;
使用.addHeader(String key,String value),即使當(dāng)前的可以已經(jīng)存在值了,只會(huì)添加新value的值,并不會(huì)移除/替換原來的值。
private final OkHttpClient client = new OkHttpClient();
public void run() throws Exception {
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();
Response response = client.newCall(request).execute();
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
System.out.println("Server: " + response.header("Server"));
System.out.println("Date: " + response.header("Date"));
System.out.println("Vary: " + response.headers("Vary"));
}
2、okhttp3 Post 方法
2.1 、Post 提交鍵值對
很多時(shí)候,我們需要通過Post方式把鍵值對數(shù)據(jù)傳送到服務(wù)器,okhttp3使用FormBody.Builder創(chuàng)建請求的參數(shù)鍵值對;
private void okHttp_postFromParameters() {
new Thread(new Runnable() {
@Override
public void run() {
try {
// 請求完整url:http://api.k780.com:88/?app=weather.future&weaid=1&&appkey=10003&sign=b59bc3ef6191eb9f747dd4e83c99f2a4&format=json
String url = "http://api.k780.com:88/";
OkHttpClient okHttpClient = new OkHttpClient();
String json = "{'app':'weather.future','weaid':'1','appkey':'10003'," +
"'sign':'b59bc3ef6191eb9f747dd4e83c99f2a4','format':'json'}";
RequestBody formBody = new FormBody.Builder().add("app", "weather.future")
.add("weaid", "1").add("appkey", "10003").add("sign",
"b59bc3ef6191eb9f747dd4e83c99f2a4").add("format", "json")
.build();
Request request = new Request.Builder().url(url).post(formBody).build();
okhttp3.Response response = okHttpClient.newCall(request).execute();
Log.i(TAG, response.body().string());
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
2.2 、Post a String
可以使用Post方法發(fā)送一串字符串,但不建議發(fā)送超過1M的文本信息,如下示例展示了,發(fā)送一個(gè)markdown文本
public static final MediaType MEDIA_TYPE_MARKDOWN
= MediaType.parse("text/x-markdown; charset=utf-8");
private final OkHttpClient client = new OkHttpClient();
public void run() throws Exception {
String postBody = ""
+ "Releases\n"
+ "--------\n"
+ "\n"
+ " * _1.0_ May 6, 2013\n"
+ " * _1.1_ June 15, 2013\n"
+ " * _1.2_ August 11, 2013\n";
Request request = new Request.Builder()
.url("https://api.github.com/markdown/raw")
.post(RequestBody.create(MEDIA_TYPE_MARKDOWN, postBody))
.build();
Response response = client.newCall(request).execute();
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
System.out.println(response.body().string());
}
2.3 、Post Streaming
post可以將stream對象作為請求體,依賴以O(shè)kio 將數(shù)據(jù)寫成輸出流形式;
public static final MediaType MEDIA_TYPE_MARKDOWN
= MediaType.parse("text/x-markdown; charset=utf-8");
private final OkHttpClient client = new OkHttpClient();
public void run() throws Exception {
RequestBody requestBody = new RequestBody() {
@Override public MediaType contentType() {
return MEDIA_TYPE_MARKDOWN;
}
@Override public void writeTo(BufferedSink sink) throws IOException {
sink.writeUtf8("Numbers\n");
sink.writeUtf8("-------\n");
for (int i = 2; i <= 997; i++) {
sink.writeUtf8(String.format(" * %s = %s\n", i, factor(i)));
}
}
private String factor(int n) {
for (int i = 2; i < n; i++) {
int x = n / i;
if (x * i == n) return factor(x) + " × " + i;
}
return Integer.toString(n);
}
};
Request request = new Request.Builder()
.url("https://api.github.com/markdown/raw")
.post(requestBody)
.build();
Response response = client.newCall(request).execute();
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
System.out.println(response.body().string());
}
2.4 、Post file
public static final MediaType MEDIA_TYPE_MARKDOWN
= MediaType.parse("text/x-markdown; charset=utf-8");
private final OkHttpClient client = new OkHttpClient();
public void run() throws Exception {
File file = new File("README.md");
Request request = new Request.Builder()
.url("https://api.github.com/markdown/raw")
.post(RequestBody.create(MEDIA_TYPE_MARKDOWN, file))
.build();
Response response = client.newCall(request).execute();
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
System.out.println(response.body().string());
}
3、其他配置
3.1 、Gson解析Response的Gson對象
如果Response對象的內(nèi)容是個(gè)json字符串,可以使用Gson將字符串格式化為對象。ResponseBody.charStream()使用響應(yīng)頭中的Content-Type 作為Response返回?cái)?shù)據(jù)的編碼方式,默認(rèn)是UTF-8。
private final OkHttpClient client = new OkHttpClient();
private final Gson gson = new Gson();
public void run() throws Exception {
Request request = new Request.Builder()
.url("https://api.github.com/gists/c2a7c39532239ff261be")
.build();
Response response = client.newCall(request).execute();
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
Gist gist = gson.fromJson(response.body().charStream(), Gist.class);
for (Map.Entry<String, GistFile> entry : gist.files.entrySet()) {
System.out.println(entry.getKey());
System.out.println(entry.getValue().content);
}
}
static class Gist {
Map<String, GistFile> files;
}
static class GistFile {
String content;
}
3.2 、okhttp3 本地緩存
okhttp框架全局必須只有一個(gè)OkHttpClient實(shí)例(new OkHttpClient()),并在第一次創(chuàng)建實(shí)例的時(shí)候,配置好緩存路徑和大小。只要設(shè)置的緩存,okhttp默認(rèn)就會(huì)自動(dòng)使用緩存功能。
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有點(diǎn)像Application的概念,統(tǒng)籌著整個(gè)okhttp的大功能,通過它設(shè)置緩存目錄,我們執(zhí)行上面的代碼,得到的結(jié)果如下

response1 的結(jié)果在networkresponse,代表是從網(wǎng)絡(luò)請求加載過來的,而response2的networkresponse 就為null,而cacheresponse有數(shù)據(jù),因?yàn)槲以O(shè)置了緩存因此第二次請求時(shí)發(fā)現(xiàn)緩存里有就不再去走網(wǎng)絡(luò)請求了。
但有時(shí)候即使在有緩存的情況下我們依然需要去后臺請求最新的資源(比如資源更新了)這個(gè)時(shí)候可以使用強(qiáng)制走網(wǎng)絡(luò)來要求必須請求網(wǎng)絡(luò)數(shù)據(jù)
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));
}
上面的代碼中
response2對應(yīng)的request變成
request = request.newBuilder().cacheControl(CacheControl.FORCE_NETWORK).build();
我們看看運(yùn)行結(jié)果

response2的cache response為null,network response依然有數(shù)據(jù)。
同樣的我們可以使用 FORCE_CACHE 強(qiáng)制只要使用緩存的數(shù)據(jù),但如果請求必須從網(wǎng)絡(luò)獲取才有數(shù)據(jù),但又使用了FORCE_CACHE 策略就會(huì)返回504錯(cuò)誤,代碼如下,我們?nèi)khttpclient的緩存,并設(shè)置request為FORCE_CACHE
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));
}

3.3 、okhttp3 取消請求
如果一個(gè)okhttp3網(wǎng)絡(luò)請求已經(jīng)不再需要,可以使用Call.cancel()來終止正在準(zhǔn)備的同步/異步請求。如果一個(gè)線程正在寫一個(gè)請求或是讀取返回的response,它將會(huì)接收到一個(gè)IOException。
private final ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
private final OkHttpClient client = new OkHttpClient();
public void run() 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("%.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);
}
}
3.4 、okhttp3 超時(shí)設(shè)置
okhttp3 支持設(shè)置連接超時(shí),讀寫超時(shí)。
private final OkHttpClient client;
public ConfigureTimeouts() throws Exception {
client = new OkHttpClient.Builder()
.connectTimeout(10, TimeUnit.SECONDS)
.writeTimeout(10, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS)
.build();
}
public void run() throws Exception {
Request request = new Request.Builder()
.url("http://httpbin.org/delay/2") // This URL is served with a 2 second delay.
.build();
Response response = client.newCall(request).execute();
System.out.println("Response completed: " + response);
}
3.5 、okhttp3 復(fù)用okhttpclient配置
所有HTTP請求的代理設(shè)置,超時(shí),緩存設(shè)置等都需要在OkHttpClient中設(shè)置。如果需要更改一個(gè)請求的配置,可以使用 OkHttpClient.newBuilder()獲取一個(gè)builder對象,該builder對象與原來OkHttpClient共享相同的連接池,配置等。
如下示例,拷貝2個(gè)'OkHttpClient的配置,然后分別設(shè)置不同的超時(shí)時(shí)間;
private final OkHttpClient client = new OkHttpClient();
public void run() throws Exception {
Request request = new Request.Builder()
.url("http://httpbin.org/delay/1") // This URL is served with a 1 second delay.
.build();
try {
// Copy to customize OkHttp for this request.
OkHttpClient copy = client.newBuilder()
.readTimeout(500, TimeUnit.MILLISECONDS)
.build();
Response response = copy.newCall(request).execute();
System.out.println("Response 1 succeeded: " + response);
} catch (IOException e) {
System.out.println("Response 1 failed: " + e);
}
try {
// Copy to customize OkHttp for this request.
OkHttpClient copy = client.newBuilder()
.readTimeout(3000, TimeUnit.MILLISECONDS)
.build();
Response response = copy.newCall(request).execute();
System.out.println("Response 2 succeeded: " + response);
} catch (IOException e) {
System.out.println("Response 2 failed: " + e);
}
}
3.6 、okhttp3 處理驗(yàn)證
okhttp3 會(huì)自動(dòng)重試未驗(yàn)證的請求。當(dāng)一個(gè)請求返回401 Not Authorized時(shí),需要提供Anthenticator。
private final OkHttpClient client;
public Authenticate() {
client = new OkHttpClient.Builder()
.authenticator(new Authenticator() {
@Override public Request authenticate(Route route, Response response) throws IOException {
System.out.println("Authenticating for response: " + response);
System.out.println("Challenges: " + response.challenges());
String credential = Credentials.basic("jesse", "password1");
return response.request().newBuilder()
.header("Authorization", credential)
.build();
}
})
.build();
}
public void run() throws Exception {
Request request = new Request.Builder()
.url("http://publicobject.com/secrets/hellosecret.txt")
.build();
Response response = client.newCall(request).execute();
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
System.out.println(response.body().string());
}
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
解決Android Studio 3.0 butterknife:7.0.1配置的問題
下面小編就為大家分享一篇解決Android Studio 3.0 butterknife:7.0.1配置的問題,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2017-12-12
Android開發(fā)實(shí)現(xiàn)在TextView前面加標(biāo)簽示例
這篇文章主要為大家介紹了Android開發(fā)實(shí)現(xiàn)TextView前面加標(biāo)簽示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-04-04
Android自定義View實(shí)現(xiàn)地鐵顯示牌效果
這篇文章主要為大家詳細(xì)介紹了Android自定義View實(shí)現(xiàn)地鐵顯示牌效果,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-11-11
Android 實(shí)現(xiàn)為點(diǎn)擊事件添加震動(dòng)效果
這篇文章主要介紹了Android 實(shí)現(xiàn)為點(diǎn)擊事件添加震動(dòng)效果,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-03-03
Android Flutter實(shí)現(xiàn)上拉加載組件的示例代碼
既然列表有下拉刷新外當(dāng)然還有上拉加載更多操作了,本次就為大家詳細(xì)介紹如何利用Flutter實(shí)現(xiàn)為列表增加上拉加載更多的交互,感興趣的可以了解一下2022-08-08
Android?studio實(shí)現(xiàn)app登錄界面
這篇文章主要為大家詳細(xì)介紹了Android?studio實(shí)現(xiàn)app登錄界面,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-04-04
Android自定義View實(shí)現(xiàn)球形動(dòng)態(tài)加速球
這篇文章主要為大家詳細(xì)介紹了Android自定義View實(shí)現(xiàn)球形動(dòng)態(tài)加速球,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-06-06

