我們寫了一些例子來演示怎么使用OkHttp解決通用的問題,通過閱讀這些例子來學習怎么組織所有的事情。自由復制粘貼這些例子。
Synchronous Get
下載一個文件,打印響應頭和響應體轉化后的字符串。
對于小的文檔response body的<code>String()</code>方法是方便且高效的。但是如果response body比較到大(>1M)應避免使用<code>String()</code>方法,因為這將把整個文檔導入內存。這種情況下,優(yōu)先吧response body作為流使用。
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());
}
Asynchronous Get
在工作線程下載文件,在response響應時回調。當響應頭準備好時調用回調函數。讀取response body可能阻塞線程。OkHttp目前沒有提供獲取response body 部分內容的API。
private final OkHttpClient client = new OkHttpClient();
public void run() throws Exception {
Request request = new Request.Builder()
.url("http://publicobject.com/hellowworld.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 = resonseHeaders.size(); i < size;i++) {
System.out.println(responseHeaders.name(i) + ":" + responseHeaders.value(i));
}
System.out.println(response.body().string());
}
});
}
Accessing Headers
一般HTTP頭的就像一個<code>Map<String, String></code>:每個字段對應一個值或空值。但是一些頭允許多個值就像Guava的Multimap。比如一個HTTP的response支持多個<code>Vary</code>頭。OkHttp的API試圖使這些情況的使用更舒服。
當寫請求頭時使用<code>header(name, value)</code>設置唯一的name對應的value。當一個name對應多個value時,新的設置的value會替換原來的value。使用<code>addHeader(name, value)</code>添加的頭不會覆蓋原有的頭。
當讀取response中的一個頭時,使用<code>header(name)</code>將返回最后一個name的值。一般情況也只有一個。如果沒有value對應<code>header(name)</code>將返回null,<code>headers(name)</code>將返回一個當前name對應value的list。
要訪問所有的頭,使用<code>Headers</code>類,這個類支持索引訪問。
private final OkHttpClient client = new OkHttpClient();
public void run() throws Exception {
Request request = new Request.Builder()
.url("http://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("Unexcepted code " + response);
System.out.prinln("Server: " + response.header("Server"));
System.out.prinln("Date: " + response.header("Date"));
System.out.prinln("Vary: " + response.headers("Vary"));
}
Posting a String
用HTTP POST 發(fā)送請求體到服務器。 這個例子發(fā)送了一個markdown文件到web服務器把markdown作為HTML展示。當請求體大于1M時應該避免使用這個API因為它會把請求體全部保存到內存中。
public static final MediaType MEDIA_TYPE_MARKDOWN = MediaType.parse("text/x-markdown; charset=utf-8");
private final OkHttoClient client = new OkHttpClient();
public void run() throws IOException {
String postBody = ""
+ "Release\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("http://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 Streaming
這里我們將請求體作為流提交(POST方式)。請求體的內容在它開始寫的時候生成。這個例子流將直接寫入 Okio 的緩沖槽。你編程時可能更傾向于<code>OutputStream</code>, 你可以通過<code>BufferedSink.outputStream()</code>獲取。
public static final MediaType MEDIA_TYPE_MARKDOWN =
MediaType.parse("text/x-markdown; cjarset=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) + x +" x " +i;
}
return Integer,toString(n);
}
}
};
Response response = client.newCall(request).execute();
if (!response.isSuccessful())
throw new IOException("Unexcepted code " + response);
System.out.println(response.body().string());
}
Posting a File
使用文件作為請求體是非常方便的。
public static final MediaType MEDIA_TYPE_MARKDOWN = MediaType.parse("text/x-markdown; charset=utf-8");
private final OkHttoClient client = new OkHttpClient();
public void run() throws IOException {
File file = new File("README.md");
Request request = new Request.Builder()
.url("http://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());
}
Posting form parameters
用<code>FormBody.Builder</code>創(chuàng)建請求體是可以的就像HTML的<code><form></code>標簽。鍵和值將URL編碼來兼容HTML表單。
private final OkHttoClient client = new OkHttpClient();
public void run() throws IOException {
RequestBody formBody = new FormBody.Builder()
.add("search", "Jurassic Park")
.build();
Request request = new Request.Builder()
.url("http://api.github.com/markdown/raw")
.post(formBody)
.build();
Response response = client.newCall(request).execute();
if (!response.isSuccessful())
throw new IOException("Unexpected code " + response);
System.out.println(response.body().string());
}
Posting a multipart request
<code>MultipartBody.Builder</code>用于創(chuàng)建復雜的請求體來兼容HTML文件上傳。復雜請求體的每一部分本事就是一個請求體,能夠定義其本身的頭。目前,這些頭應該描述每一部分的請求體,就像它本身的<code>Content-Disposition</code>。<code>Content-Length</code>和<code>Content-Type</code>頭將在可用時自動添加。
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 document at https://api.imgur.com/endpoints.image
RequestBody requestBody = new MultipartBody.Bulder()
.setType(MultiparBody.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("Autorization", "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());
}
Parse a JSON Response With Gson
Gson 是一個處理JSON字符串與java對象轉換的好用的API。這里我們使用Gson來解析從GitHub API獲取的JSON。
注意<code>ResponseBody.charStream()</code>方法將使用從響應頭中獲取的<code>Content-Type</code>值作為響應體的解碼格式。在沒有指定的情況下將使用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.budy.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;
}
Response Caching
使用本地緩存response需要提供一個可以讀寫的緩存路徑,和緩存的大小。這個緩存路徑應該是私有的,不可信的應用不可以讀取緩存的內容!
多個本地緩存使用同一個路徑是錯誤的,大部分的應用都應該調用<code>new OkHttpClient()</code>的同時配置緩存,并且保證在任何地方都是使用的同一個。否則兩個緩存會相互影響,污染response緩存,甚至使你的程序崩潰。
response 緩存會從的HTTP頭讀取配置。你可以添加一個像<code>Cache-Control: max-stale=3600</code>的請求頭,OkHttp緩存就會遵守。你的服務器通過response頭配置response的緩存時間(就像<code>Cache-Control:max-age=9600</code>)。有些緩存頭可以控制緩存的response,控制一個網絡緩存,或者通過可選的GET驗證控制一個網絡的response。
private final OkHttpClient client;
public CacheResponse(File cahceDirectory) throws Exception {
int cacheSize = 10 * 1024 * 1024; //10MiB
Cache cache = new Cache(cacheDirctory, cacheSize);
client = new OkHttpClient.Builder()
.cache(cache)
.build();
}
public void run() throws Exception {
Reques 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 " + response);
String response1Body = response1.body().string();
System.out.println("Response 1 response: " + response1);
System.out.println("Response 1 cache response: " + response1.cahceResponse());
System.out.println("Response 1 network response: " + response1.networkResponse());
Response response2 = client.newCall(request).execute();
if(!response2.isSuccessful())
throw new IOException("Unexpected code " + response);
String response2Body = response2.body().string();
System.out.println("Response 2 response: " + response2);
System.out.println("Response 2 cache response: " + response1.cahceResponse());
System.out.println("Response 2 network response: " + response2.networkResponse());
System.out.println("Response 2 equals Response 1?:" + response1Body.equals(response2Body));
}
通過使用<code>CacheControl.FORCE_NETWORK</code>可以阻止使用本地緩存,<code>CacheControl.FORCE_CACHE</code>可以阻止網絡緩存。警告:如果你使用了<code>FORCE_CACHE</code>response需要使用網絡,否則OkHttp將返回<code>504 Unsatisfiable Request</code>response。
(*注:關于緩存的內容可以參考這里)
Canceling a Call
<code>Call.cancel()</code>可以立刻取消正在進行的call。如果當前的線程正在寫request或者讀response將導致<code>IOException</code>。通過取消不必要的call可以節(jié)省流量;當你通過導航離開應用時應用的同步或異步call都可以被取消。
private final ScheduleExecutorService 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")
.build();
final long startNanos = System.nanoTime();
final Call call = client.newCall(request);
// Scheduler a jod 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 Canceling call.%n", (System.nanoTime() - startNanos) / 1e9f);
}
}, 1, TimeUnit.SECONDS);
try {
System.out.prinf("%.2f Canceling call.%n", (System.nanoTime() - startNanos) / 1e9f);
Response response = call.execute();
System.out.prinf("%.2f Canceling call.%S%n", (System.nanoTime() - startNanos) / 1e9f, response);
} catch(IOException e) {
System.out.prinf("%.2f Canceling call.%S%n", (System.nanoTime() - startNanos) / 1e9f, e);
}
}
Timeouts
訪問超時取消的call等同于網絡不能訪問,網絡分區(qū)可能引起客戶端的連接問題,或者服務器的不可用問題。OkHttp支持設置連接,讀,寫的超時。
private final OkHttpClient client;
public ConfigureTimeouts() thows Exception {
client = new OkHttpCLient.Builder()
.connectTimeout(10, TimeUnit.SECONDS)
.writeTimeout(10, TimeUnit.SECONDS)
.readeTimeout(30, TimeUnit.SECONDS)
.build();
}
public void run() throws Exception {
Requets requets = new Request.Builder()
.url("http://httpbin.org.delay/2")
.build();
Response response = client.newCall(request).execute();
System.out.prinln("Response completed: " + response);
}
Per-call Configuration
所有的HTTP客戶端配置依賴于<code>OkHttpClient</code>,包括代理設置,超時,和緩存。當你需要改變某個call的配置時,調用<code>OkHttpClient.newBuilder()</code>將返回與源客戶端公用pool,dispatcher,和配置的一個構造者。在下一個例子中,我們創(chuàng)建了一個請求分別具有500ms的超時和3000ms的超時。
private final OkHttpClient client = new OkHttpClient();
public void run() throws Exception {
Request request = new Request.Builder()
.url("http://httpbin.org/delay/1")
.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);
}
}
Handling authentication
當一個request的返回碼是<code>401 Not Authorized</code>時OkHttp 可以自動重試未授權的requests。 <code>Authenticator</code>用于提供證書。Authenticator的實現應該構建一個帶有確實認證的request,在沒有認證可用時通過返回null來跳過重試。
<code>Response.challenges()</code>方法可以獲取授權問題的scheme 和 realm,<code>Basic</code> 認證可以使用<code>Credentials.basic(username, password)</code>來編碼請求頭。
(*注:關于認證)
private final OkHttpClient client;
public Authenticate() {
client = new OkHttpClient.Builder()
.authenticator(new Autenticator() {
@Override public Request authenticate(Routr rourte, Response response) throws IOException {
System.out.println("Authenicating for response: " + response);
System.out.println("Challenges: " + response.challenges());
String credential = Credentials.basic("jesse", "password1");
return response.request().newBuilder()
.header("Authorization", crebential)
.build();
}
})
.build();
}
public void run() tthrows Exception {
Request request = new Request.Builder()
.url("http://publicobjetc.com/secrets/hellosecret.txt")
.build();
Response response = client.newCall(request).execute();
if (!response.isSuccessfun()) throw new IOException("Unexpected code" + response);
System.out.println(response.body().string());
}
通過返回null避免認證失敗時的多次重試。例如在已經重試的情況下結束重試:
if(credentical.equals(response.request().header("Authorization"))) {
return null; // If We already failde with these credentials, don't retry.
}
你也可以設置重試的次數:
if (responseCount(response) >= 3) {
return null; // If We've failed 3 times, give up.
}
private int responseCount(Reponse response) {
int result = 1;
while ((response = response.priorResponse()) != null) {
result ++;
}
return result;
}