|
1 | 1 | package io.github.kimmking.gateway.outbound.okhttp; |
2 | 2 |
|
| 3 | +import cn.hutool.json.JSONUtil; |
| 4 | +import okhttp3.*; |
| 5 | + |
| 6 | +import java.io.IOException; |
| 7 | + |
3 | 8 | public class OkhttpOutboundHandler { |
| 9 | + private OkHttpClient okHttpClient = new OkHttpClient(); |
| 10 | + |
| 11 | + public String base_url = "http://localhost:8801"; |
| 12 | + |
| 13 | + /** |
| 14 | + * get 请求,常用于获取请求 |
| 15 | + * |
| 16 | + * @param api |
| 17 | + */ |
| 18 | + public void testGet(String api) throws IOException { |
| 19 | + Request request = new Request.Builder() |
| 20 | + .url(base_url + api) |
| 21 | + .get() |
| 22 | + .build(); |
| 23 | + Call call = okHttpClient.newCall(request); |
| 24 | + Response response = call.execute(); |
| 25 | + System.out.println(response.body().toString()); |
| 26 | + |
| 27 | + } |
| 28 | + |
| 29 | + /** |
| 30 | + * put 请求,常用于更新请求 |
| 31 | + * |
| 32 | + * @param api |
| 33 | + */ |
| 34 | + public void testPut(String api) throws IOException { |
| 35 | + TestModel testModel = new TestModel(); |
| 36 | + RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), |
| 37 | + JSONUtil.toJsonStr(testModel)); |
| 38 | + Request request = new Request.Builder() |
| 39 | + .url(base_url + api) |
| 40 | + .put(requestBody) |
| 41 | + .build(); |
| 42 | + Call call = okHttpClient.newCall(request); |
| 43 | + Response response = call.execute(); |
| 44 | + System.out.println(response.body().toString()); |
| 45 | + } |
| 46 | + |
| 47 | + /** |
| 48 | + * POST 请求,常用于新增或复杂的获取请求 |
| 49 | + * |
| 50 | + * @param api |
| 51 | + */ |
| 52 | + public void testPost(String api) throws IOException { |
| 53 | + TestModel testModel = new TestModel(); |
| 54 | + RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), |
| 55 | + JSONUtil.toJsonStr(testModel)); |
| 56 | + Request request = new Request.Builder() |
| 57 | + .url(base_url + api) |
| 58 | + .post(requestBody) |
| 59 | + .build(); |
| 60 | + Call call = okHttpClient.newCall(request); |
| 61 | + Response response = call.execute(); |
| 62 | + System.out.println(response.body().toString()); |
| 63 | + } |
| 64 | + |
| 65 | + /** |
| 66 | + * DELETE 请求,常用于删除请求 |
| 67 | + * |
| 68 | + * @param api |
| 69 | + */ |
| 70 | + public void testDelete(String api) throws IOException { |
| 71 | + Request request = new Request.Builder() |
| 72 | + .url(base_url + api) |
| 73 | + .delete() |
| 74 | + .build(); |
| 75 | + Call call = okHttpClient.newCall(request); |
| 76 | + Response response = call.execute(); |
| 77 | + System.out.println(response.body().toString()); |
| 78 | + } |
| 79 | + |
| 80 | + private class TestModel { |
| 81 | + private Integer testVo; |
| 82 | + } |
| 83 | + |
4 | 84 | } |
0 commit comments