我們寫了一些方法來示例如果使用OkHttp來解決常見問題。通讀它們了解它們是如何一起工作的。隨意地進行復(fù)制、粘貼,這是它們存在的目的。
同步Get請求
下載一個文件,打印它的頭,并將其響應(yīng)主體以字符串形式打印。
作用在響應(yīng)主體上的string()方法對于小文檔來說是方便和高效的。但是如果響應(yīng)主體比較大(大于1MB),避免使用string(),因為它會加載整個文檔到內(nèi)存中。在這種情況下,優(yōu)先使用stream來處理主體。
private final OkHttpClient client = new OkHttpClient();
public void run() throws Exception {
Request request = new Request.Builder()
.url("http://publicobject.com/helloworld.txt")
.build();
Response response = client.newCall(request).execute();
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
Headers responseHeaders = response.headers();
for (int i = 0; i < responseHeaders.size(); i++) {
System.out.println(responseHeaders.name(i) + ": " + responseHeaders.value(i));
}
System.out.println(response.body().string());
}
異步Get請求
在一個工作線程下載一個文件,當響應(yīng)可讀時獲取回調(diào)。這個回調(diào)將在響應(yīng)頭準備好時執(zhí)行。讀取響應(yīng)主體可能仍然阻塞。OkHttp當前沒有提供異步API來局部地接收響應(yīng)主體。
private final OkHttpClient client = new OkHttpClient();
public void run() throws Exception {
Request request = new Request.Builder()
.url("http://publicobject.com/helloworld.txt")
.build();
client.newCall(request).enqueue(new Callback() {
@Override public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
@Override public void onResponse(Call call, Response response) throws IOException {
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
Headers responseHeaders = response.headers();
for (int i = 0, size = responseHeaders.size(); i < size; i++) {
System.out.println(responseHeaders.name(i) + ": " + responseHeaders.value(i));
}
System.out.println(response.body().string());
}
});
}
訪問Header
典型的HTTP頭工作起來像一個Map< String, String >,每一個字段有一個值或沒有值。但是有一些頭允許多個值,像Guava的Multimap。對于一個HTTP響應(yīng)來應(yīng)用多個Vary頭是合法的并且常見的。OkHttp的API試圖兼容這些情況。
當寫請求頭時,使用header(name, value)的方式來設(shè)置唯一出現(xiàn)的鍵值。如果已有值,會在新值添加前移除已有值。使用addHeader(name, value)來添加一個頭而不移除已經(jīng)存在的頭。
當讀取一個響應(yīng)頭時,使用header(name)來返回最后一次出現(xiàn)的鍵值對。通常這是唯一出現(xiàn)的鍵值對。如果不存在值,header(name)會返回null。使用headers(name)來用一個list讀取一個字段的所有值。
使用支持按索引訪問的Headers類來訪問所有的頭。
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"));
}
上傳字符串
使用HTTP POST來發(fā)送請求主體到服務(wù)器。這個例子上傳了一個markdown文檔到一個用HTML渲染markdown的服務(wù)器中。因為整個請求主體同時存在內(nèi)存中,避免使用這個API上傳大的文檔(大于1MB)。
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());
}
上傳流
這里以stream的形式上傳請求主體。請求主體的內(nèi)容如它寫入的進行生成。這個示例stream直接放入到了Okio緩存sink中。你的程序可能需要一個OutputStream,你可以從BufferedSink.outputStream()中獲取。
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());
}
上傳文件
使用文件作為請求主體很容易。
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());
}
上傳表格參數(shù)
使用FormBody.Builder來構(gòu)建一個工作起來像HTML< form >標簽的請求主體。鍵值對會使用一個兼容HTML form的URL編碼進行編碼。
private final OkHttpClient client = new OkHttpClient();
public void run() throws Exception {
RequestBody formBody = new FormBody.Builder()
.add("search", "Jurassic Park")
.build();
Request request = new Request.Builder()
.url("https://en.wikipedia.org/w/index.php")
.post(formBody)
.build();
Response response = client.newCall(request).execute();
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
System.out.println(response.body().string());
}
上傳多部分請求
MultipartBody.Builder可以構(gòu)造復(fù)雜的請求主體與HTML文件上傳表單兼容。multipart請求主體的每部分本身就是一個請求主體,可以定義它自己的頭。如果存在自己的頭,那么這些頭應(yīng)該描述部分主體,例如它的Content-Disposition。Content-Length和Content-Type會在其可用時自動添加。
private static final String IMGUR_CLIENT_ID = "...";
private static final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");
private final OkHttpClient client = new OkHttpClient();
public void run() throws Exception {
// Use the imgur image upload API as documented at https://api.imgur.com/endpoints/image
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("title", "Square Logo")
.addFormDataPart("image", "logo-square.png",
RequestBody.create(MEDIA_TYPE_PNG, new File("website/static/logo-square.png")))
.build();
Request request = new Request.Builder()
.header("Authorization", "Client-ID " + IMGUR_CLIENT_ID)
.url("https://api.imgur.com/3/image")
.post(requestBody)
.build();
Response response = client.newCall(request).execute();
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
System.out.println(response.body().string());
}
使用Gson解析Json響應(yīng)
Gson是一個便利API來實現(xiàn)JSON和Java對象之間的轉(zhuǎn)化。這里我們使用它來解碼來自GitHub API的JSON響應(yīng)。
ResponseBody.charStream()使用響應(yīng)頭Content-Type來確定在解碼響應(yīng)主體時使用哪個字符集。如果沒有指定字符集,則默認使用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;
}
響應(yīng)緩存
要緩存響應(yīng),你需要一個進行讀取和寫入的緩存目錄,以及一個緩存大小的限制。緩存目錄應(yīng)該是私有的,且不被信任的應(yīng)用不能夠讀取它的內(nèi)容。
讓多個緩存同時訪問相同的混存目錄是錯誤的。大多數(shù)應(yīng)用應(yīng)該只調(diào)用一次new OkHttpClient(),配置它們的緩存,并在所有地方使用相同的實例。否則兩個緩存實例會相互進行干涉,腐朽響應(yīng)緩存,有可能造成你的程序崩潰。
響應(yīng)緩存使用HTTP頭進行所有配置。你可以添加像Cache-Control:max-stale=3600這樣的請求頭并且OkHttp的緩存會尊重它們。你的服務(wù)器使用自己的響應(yīng)頭像Cache-Control:max-age=9600來配置響應(yīng)緩存多久。這里有緩存頭來強制一個緩存響應(yīng),強制一個網(wǎng)絡(luò)響應(yīng),強制使用一個條件的GET來驗證網(wǎng)絡(luò)響應(yīng)。
private final OkHttpClient client;
public CacheResponse(File cacheDirectory) throws Exception {
int cacheSize = 10 * 1024 * 1024; // 10 MiB
Cache cache = new Cache(cacheDirectory, cacheSize);
client = new OkHttpClient.Builder()
.cache(cache)
.build();
}
public void run() 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));
}
使用CacheControl.FORCE_NETWORK來阻止響應(yīng)使用緩存。使用CacheContril.FORCE_CACHE來阻止使用網(wǎng)絡(luò)。注意:如果你使用FORCE_CACHE且響應(yīng)需要網(wǎng)絡(luò),OkHttp會返回一個504 Unsatisfiable Request響應(yīng)。
取消調(diào)用
使用Call.cancel()來立即停止一個正在進行的調(diào)用。如果一個線程正在寫請求或讀響應(yīng),它會接收到一個IOException。當一個調(diào)用不再需要時,使用這個來節(jié)省網(wǎng)絡(luò),例如當用戶從應(yīng)用離開。同步和異步調(diào)用都可以取消。
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);
}
}
超時
使用超時來使調(diào)用在當另一端沒有到達時失敗。網(wǎng)絡(luò)部分可能是由于連接問題,服務(wù)器可用性問題或者其他。OkHttp支持連接、讀取和寫入超時。
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);
}
單獨配置調(diào)用
所有HTTP client配置都存在OkHttpClient中,包括代理設(shè)置,超時和緩存。當你需要改變一個單獨call的配置時,調(diào)用OkHttpClient.newBuilder()。這個會返回一個builder,與原始的client共享下共同的連接池,調(diào)度器和配置。在下面的例子中,我們讓一個請求有500ms的超時而另一個有3000ms的超時。
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);
}
}
處理認證
OkHttp會自動重試未認證請求。當一個響應(yīng)為401 Not Authorized時,會要求Authenticator來應(yīng)用證書。Authenticator的實現(xiàn)應(yīng)該構(gòu)建一個包含缺失證書的新請求。如果沒有證書可用,返回null來跳過重試。
使用Response.challenges()來獲取所有認證挑戰(zhàn)的模式和領(lǐng)域。當完成一個Basic挑戰(zhàn)時,使用Credentials.basic(username,password)來編碼請求頭。
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());
}
為了避免當認證無法工作時過多的嘗試,你可以返回null來放棄。例如,當這些明確的證書已經(jīng)嘗試過了,你可能想跳過。
if (credential.equals(response.request().header("Authorization"))) {
return null; // If we already failed with these credentials, don't retry.
}
你可能也想在達到應(yīng)用定義的嘗試限制次數(shù)時跳過嘗試:
if (respondseCount(response) >= 3) {
return null; // If we've failed 3 times, give up.
}
上面的代碼依賴這個responseCount()方法:
private int responseCount(Response response) {
int result = 1;
while ((response = response.priorResponse()) != null) {
result++;
}
return result;
}
原文鏈接:
https://github.com/square/okhttp/wiki/Recipes
OkHttp官方文檔系列文章: