//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还有下载的功能,而你又使用的是单例模式,所以你
搭建框架的时候一定要做好区分。
复制代码