okhttp文档的Recipe的翻译,记录okhttp的请求方法以及取消方式
1 同步的GET
下载一个文件,打印它的头文件,并将它的响应体打印为字符串。
对于小文档,响应体上的string()方法非常方便和高效。但是,如果响应主体很大(大于1 MiB),则应避免使用string(),因为它会将整个文档加载到内存中。在这种情况下,最好将正文作为流处理。
private final OkHttpClient client = new OkHttpClient();
public void run() throws Exception {
Request request = new Request.Builder()
.url("https://publicobject.com/helloworld.txt")
.build();
try (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());
}
}
2 异步 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 {
try (ResponseBody responseBody = response.body()) {
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
Headers responseHeaders = response.headers();
for (int i = 0, size = responseHeaders.