//GET A URL
//This program downloads a URL and print its contents as a string. Full source.
OkHttpClient client = new OkHttpClient();
String run(String url) throws IOException {
Request request = new Request.Builder()
.url(url)
.build();
//同步請求
Response response = client.newCall(request).execute();
return response.body().string();
}
//POST TO A SERVER
//This program posts data to a service. Full source.
public static final MediaType JSON
= MediaType.parse("application/json; charset=utf-8");
OkHttpClient client = new OkHttpClient();
String post(String url, String json) throws IOException {
RequestBody body = RequestBody.create(JSON, json);
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
//同步請求
Response response = client.newCall(request).execute();
return response.body().string();
}
複製程式碼
我們專案中使用,一般都要設計成單例模式,這樣才能體現出OkHttp的優勢。原文如下:
OkHttp performs best when you create a single {@code OkHttpClient} instance and reuse
it for all of your HTTP calls. This is because each client holds its own connection pool
and thread pools. Reusing connections and threads reduces latency and saves memory.
Conversely, creating a client for each request wastes resources on idle pools.
那麼問題來了,假如我要針對個別請求修改配置腫麼辦?別方,官網也給出了答案:
You can customize a shared OkHttpClient instance with {@link #newBuilder()}. This
builds a client that shares the same connection pool, thread pools, and configuration.
Use the builder methods to configure the derived client for a specific purpose.
程式碼如下:
複製程式碼
/**
* Returns a non-null value if this response was passed to {@link Callback#onResponse}
* or returned from {@link Call#execute()}. Response bodies must be {@linkplain
* ResponseBody closed} and may be consumed only once.
*
* <p>This always returns null on responses returned from {@link #cacheResponse}, {@link
* #networkResponse}, and {@link #priorResponse()}.
*/
public @Nullable ResponseBody body() {
return body;
}
複製程式碼
/**
* 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 in accordance to <a href="https://en.wikipedia.org/wiki/Byte_order_mark">
* its BOM</a> or UTF-8.
* Closes {@link ResponseBody} automatically.
*
* <p>This method loads entire response body into memory. If the response body is very
* large this may trigger an {@link OutOfMemoryError}. Prefer to stream the response
* body if this is a possibility for your response.
*/
public final String string() throws IOException {
BufferedSource source = source();
try {
Charset charset = Util.bomAwareCharset(source, charset());
return source.readString(charset);
} finally {
Util.closeQuietly(source);
}
}
複製程式碼
這裡貌似也沒有看出來什麼,只是關閉操作,那麼我們繼續往後看看
複製程式碼
/**
* Closes {@code closeable}, ignoring any checked exceptions. Does nothing if
* {@code closeable} is null.
*/
public static void closeQuietly(Closeable closeable) {
if (closeable != null) {
try {
closeable.close();
} catch (RuntimeException rethrown) {
throw rethrown;
} catch (Exception ignored) {
}
}
}
複製程式碼
/**
* Closes this stream and releases any system resources associated
* with it. If the stream is already closed then invoking this
* method has no effect.
*
* <p> As noted in {@link AutoCloseable#close()}, cases where the
* close may fail require careful attention. It is strongly advised
* to relinquish the underlying resources and to internally
* <em>mark</em> the {@code Closeable} as closed, prior to throwing
* the {@code IOException}.
*
* @throws IOException if an I/O error occurs
*/
public void close() throws IOException;
複製程式碼
廢了老大勁了,終於看明白了,然後你以為結束了?To young to simple!還是sting()方法,
他的註釋上還有一句提示 This method loads entire response body into memory. If the
response body is very large this may trigger an {@linkOutOfMemoryError}. Prefer to
stream the response body if this is a possibility for your response.
這句話很重要,他的意思是string()去讀取資料的時候,stream流不能太大,不然會導致內
存溢位。為什麼要強調這個呢?因為OKHttp還有下載的功能,而你又使用的是單例模式,所以你
搭建框架的時候一定要做好區分。
複製程式碼