|
| 1 | +package io.github.dunwu.javatech.http; |
| 2 | + |
| 3 | +import lombok.extern.slf4j.Slf4j; |
| 4 | +import okhttp3.*; |
| 5 | +import org.junit.jupiter.api.DisplayName; |
| 6 | +import org.junit.jupiter.api.Test; |
| 7 | + |
| 8 | +import java.io.IOException; |
| 9 | + |
| 10 | +/** |
| 11 | + * okhttp API 测试 |
| 12 | + * |
| 13 | + * @author Zhang Peng |
| 14 | + * @date 2022-06-09 |
| 15 | + */ |
| 16 | +@Slf4j |
| 17 | +public class OkHttpTests { |
| 18 | + |
| 19 | + OkHttpClient client = new OkHttpClient(); |
| 20 | + |
| 21 | + @Test |
| 22 | + @DisplayName("OkHttp 同步 Get 请求") |
| 23 | + public void testSyncGet() throws IOException { |
| 24 | + String ip = "127.0.0.1"; |
| 25 | + String url = "http://realip.cc/?ip=" + ip; |
| 26 | + Request request = new Request.Builder().url(url).build(); |
| 27 | + |
| 28 | + try (Response response = client.newCall(request).execute()) { |
| 29 | + String json = response.body().string(); |
| 30 | + System.out.println("请求结果:" + json); |
| 31 | + } |
| 32 | + } |
| 33 | + |
| 34 | + @Test |
| 35 | + @DisplayName("OkHttp 异步 Get 请求") |
| 36 | + public void testAsyncGet() { |
| 37 | + String ip = "127.0.0.1"; |
| 38 | + String url = "http://realip.cc/?ip=" + ip; |
| 39 | + Request request = new Request.Builder().url(url).build(); |
| 40 | + |
| 41 | + client.newCall(request).enqueue(new Callback() { |
| 42 | + @Override |
| 43 | + public void onFailure(Call call, IOException e) { |
| 44 | + e.printStackTrace(); |
| 45 | + } |
| 46 | + |
| 47 | + @Override |
| 48 | + public void onResponse(Call call, Response response) throws IOException { |
| 49 | + if (!response.isSuccessful()) |
| 50 | + throw new IOException("Unexpected code " + response); |
| 51 | + |
| 52 | + Headers responseHeaders = response.headers(); |
| 53 | + for (int i = 0, size = responseHeaders.size(); i < size; i++) { |
| 54 | + System.out.println(responseHeaders.name(i) + ": " + responseHeaders.value(i)); |
| 55 | + } |
| 56 | + |
| 57 | + String json = response.body().string(); |
| 58 | + System.out.println("请求结果:" + json); |
| 59 | + } |
| 60 | + }); |
| 61 | + } |
| 62 | + |
| 63 | +} |
0 commit comments