How To Use OKHttp For Java
這篇介紹How To Use OKHttp For Java。
Maven:add dependency in pom.xml
1 2 3 4 5 6
| <!-- https://mvnrepository.com/artifact/com.squareup.okhttp3/okhttp --> <dependency> <groupId>com.squareup.okhttp3</groupId> <artifactId>okhttp</artifactId> <version>4.9.1</version> </dependency>
|
get example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
| Synchronous: private final OkHttpClient client = new OkHttpClient(); public void SynchronousGet() 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()); } }
Asynchronous: public void AsynchronousGet() 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()); } } }); }
|
post example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| PostJson: public static final MediaType JSON = MediaType.get("application/json; charset=utf-8"); private final OkHttpClient client = new OkHttpClient(); public String PostJson(String url, String json) throws IOException { RequestBody body = RequestBody.create(json, JSON); Request request = new Request.Builder() .url(url) .post(body) .build(); try (Response response = client.newCall(request).execute()) { return response.body().string(); } } String response = PostJson("http://www.roundsapp.com/post", "{'name':'DavidChen'}");
PostForm: public void PostForm() throws Exception { RequestBody formBody = new FormBody.Builder() .add("search", "Jurassic Park") .build(); Request request = new Request.Builder() .url("https://en.wikipedia.org/w/index.php") .post(formBody) .build();
try (Response response = client.newCall(request).execute()) { if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
System.out.println(response.body().string()); } }
|