一些使用方法:
同步方法Get:
下載一個文件,打印它的頭信息,打印響應體。
response.body的string()方法用來輸出小型文檔非常方便并且效率非常高。但是假如response.body大于1M,應該避免使用string()方法,因為它將會將整個文檔加載到內存中。此時使用流更好。
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方法
在工作線程上下載文件,并在響應可讀時調用毀掉方法。 回調在響應頭準備好之后進行。 讀取響應體可能仍會阻塞線程。 OkHttp目前不提供異步API來接收部分響應體。
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());
}
});
}
訪問頭
通常HTTP的頭信息類似于Map <String,String>:每個字段有一個值或為空。 但一些頭允許多個值,如Guava的Multimap。 例如,HTTP響應提供多個Vary頭是合法且常見的。
在寫入請求標頭時,使用header(name,value)將替換頭信息。 如果有現(xiàn)有值,則在添加新值之前將刪除它們。 使用addHeader(name,value)添加頭,而不刪除已經(jīng)存在的頭。
讀取響應頭時,使用header(name)返回最后一次的值。如果沒有值,header(name)將返回null。 要將所有字段的值作為列表讀取,請使用headers(name)。
要訪問所有頭,請使用支持通過索引訪問的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"));
}
Post方法傳入字符串
使用HTTP POST將請求正文發(fā)送到服務器。此示例將markdown文檔發(fā)布到能將markdown轉換為HTML的Web服務器。由于整個請求主體都在內存中,因此請避免使用此API發(fā)布大(大于1個MiB)文檔。
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());
}
Post發(fā)送流
這里使用POST方法以流的方式發(fā)送請求。請求內容將會一邊生成一邊寫入。 此示例直接流入Okio緩沖接收器。你可能更喜歡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());
}
Post一個文件
直接看代碼:
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());
}
Post form表單
使用FormBody.Builder構建一個類似于HTML <form>標簽的請求體。 名稱和值將使用HTML兼容的表單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());
}
Post復雜體請求
MultipartBody.Builder可以構建與HTML文件上傳表單兼容的復雜請求體。 大部分請求正文的每個部分本身都是請求正文,并且可以定義其自己的頭。 這些頭信息應描述內容主體,例如其Content-Disposition。 如果Content-Length和Content-Type的header可用,則會自動添加。
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響應體
Gson是一個很方便的API,用于在JSON和Java對象之間進行轉換。 這里我們使用它來解碼來自GitHub API的JSON響應。
請注意,ResponseBody.charStream()使用Content-Type響應頭來選擇在解碼響應正文時要使用的字符集。 如果沒有指定字符集,它默認為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;
}
緩存響應
你需要為響應緩存設置一個你自己能夠讀寫的目錄,并且為這個緩存設定大小。緩存目錄必須是私有的,不被信任的程序不能訪問這個目錄。
不能使用多個緩存同時訪問同意緩存目錄。大多數(shù)應用程序應該只調用OkHttpClient()一次(就是只創(chuàng)建一個實例),否則多個實例會導致程序崩潰,破壞緩存文件。
響應緩存對所有配置使用HTTP頭。 您可以添加請求頭,如Cache-Control:max-stale = 3600,OkHttp的緩存會使用這些配置。你的網(wǎng)絡服務器會配置響應緩存持續(xù)時間的響應頭,如Cache-Control:max-age = 9600。 緩存頭強制緩存響應,強制網(wǎng)絡響應,或強制使用條件GET驗證網(wǎ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。 為了防止它使用網(wǎng)絡,請使用CacheControl.FORCE_CACHE。
Note
:如果使用FORCE_CACHE并且響應需要網(wǎng)絡,OkHttp將返回504 Unsatisfiable Request響應。
取消請求
使用Call.cancel()方法來立即他停止一個正在進行的請求。如果一個線程正在寫入一個請求或者讀取一個響應,程序將會拋出IOException異常。使用此選項可在不再需要call時節(jié)約網(wǎng)絡資源。 例如當您的用戶導航離開應用程序時,同步和異步調用都可以取消。
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);
}
}
連接超時
當連接不可達時使用timeouts來使一個請求失敗。連接問題,服務器問題或者其他都可能導致網(wǎng)絡連接失敗,OhHttp支持連接超時,讀超時和寫超時。
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);
}
單獨配置
所有HTTP客戶端配置都存在于OkHttpClient中,包括代理設置,超時和緩存。 當您需要更改單個調用的配置時,請調用OkHttpClient.newBuilder()。 這將返回與原始客戶端共享的相同連接池,調度程序和配置的構建器。 在下面的示例中,我們使用500毫秒超時創(chuàng)建一個請求,另一個請求使用3000毫秒超時。
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可以自動重試未經(jīng)身份驗證的請求。 當響應為401 Not Authorized,將要求Authenticator提供憑據(jù)。 應構建新請求包含憑證, 如果沒有可用的憑據(jù),則返回null以跳過重試。
使用Response.challenges()獲取任何身份驗證的方案和領域。 當完成基本挑戰(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());
}
你可以返回空值來放棄一個認證不通過的請求,避免多次重復本請求。例如,你可能想要跳過那些已經(jīng)嘗試過的請求。
if (credential.equals(response.request().header("Authorization"))) {
return null; // If we already failed with these credentials, don't retry.
}
你也可以跳過服務器拒絕的請求:
if (responseCount(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;
}