本文主要是介绍了如何快速使用Okhttp,由于英文能力有限,有不准确的地方,请参考原文。
原文地址https://github.com/square/okhttp/wiki/Recipes
下载一个文件,打印它的响应头信息,并以String打印响应体数据。
响应体ResponseBody的string()方法对小文档来说会更方便有效,但是如果响应体比较大(超过1MiB)请不要使用string(),因为它会把整个文档加载到内存中,这种情况下可以把响应体作为流来处理(可以使用ResponseBody的byteStream()方法);
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());
}
}
在工作线程下载文件,然后在响应可读时获得回调,这个回调在响应头准备好之后调用。这个时候读取响应体仍然会被拒绝,此时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.size(); i < size; i++) {
System.out.println(responseHeaders.name(i) + ": " + responseHeaders.value(i));
}
System.out.println(responseBody.string());
}
}
});
}
通常,HTTP的Headers工作方式如下Map
:每个字段都有一个值或没有。但是一些请求头允许有多个值比如Guava的 Multimap。比如,HTTP响应提供多个Vary
头是合法且常见的。OkHttp的API试图使两种情况都很便捷。添加请求头时,用header(name, value)
设置唯一的name和
value
。如果已经存在当前值,则在添加新值之前将删除它们。使用addHeader(name, value)
添加一个请求头时,不会移除已经存在的值。读取响应头时,用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();
try (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"));
}
}
使用HTTP POST向服务器发送请求体。这个例子将markdown文档发布到把markdown呈现为HTML的Web服务器,由于整个请求体同时在内存中,因此请避免使用此API发布大型(大于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();
try (Response response = client.newCall(request).execute()) {
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
System.out.println(response.body().string());
}
}
这个例子中我们将请求体作为流发送。请求体的内容在其开始写入时产生,此示例直接流入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();
try (Response response = client.newCall(request).execute()) {
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
System.out.println(response.body().string());
}
}
将文件作为请求体很容易。
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();
try (Response response = client.newCall(request).execute()) {
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
System.out.println(response.body().string());
}
}
使用FormBody.Builder 来构建一个请求体,就一个HTML的