【SpringBoot】7 种实现 HTTP 调用的方式

作者在工作中,遇到一些需要调用三方接口的任务,就需要用到 http 调用工具。这里,我总结了一下 实现 HTTP 调用的方式,共有 7 种(后续会继续新增),分别如下:

  • HttpClient
  • OkHttp
  • OKHttpUtil
  • Jodd HTTP
  • Hutool HTTP
  • RestTemplate
  • forest

1. HttpClient

<dependency>
	<groupId>org.apache.http***ponents</groupId>
	<artifactId>httpclient</artifactId>
	<version>4.5.6</version>
</dependency>
java">public class HttpClientUtil {

    public static String get(String url, Map<String, String> urlParam, Map<String, String> header, boolean ssl) {
        return get(url, urlParam, header, CharEncoding.UTF_8, ssl);
    }

    public static String get(String url, Map<String, String> urlParams, Map<String, String> headers, String charSet, boolean ssl) {
        HttpGet httpGet = new HttpGet(charSet == null ? addParams(url, urlParams) : addParamsWithCharSet(url, urlParams, charSet));
        return getResponse(httpGet, charSet, headers, ssl);
    }
    
    // 以请求体JSON发送数据
    public static String postJson(String url, Map<String, String> urlParams, Map<String, String> headers, String data, boolean ssl) {
        HttpPost httpPost = new HttpPost(addParams(url, urlParams));
        httpPost.setEntity(new StringEntity(data, ContentType.APPLICATION_JSON));
        return getResponse(httpPost, CharEncoding.UTF_8, headers, ssl);
    }
    
    // 以表单的形式发送数据
    public static String postForm(String url, Map<String, String> urlParams, Map<String, String> headers, Map<String, String> data, boolean ssl) {
        HttpPost httpPost = new HttpPost(addParams(url, urlParams));
        ContentType contentType = ContentType.create("application/x-www-form-urlencoded", Consts.UTF_8);
        if (Objects.isNull(headers)) {
            headers = new HashMap<>();
        }
        headers.put("Content-Type", contentType.toString());
        List<NameValuePair> list = new ArrayList<>();
        for (Map.Entry<String, String> entry : data.entrySet()) {
            list.add(new Basi***ameValuePair(entry.getKey(), entry.getValue()));
        }
        if (list.size() > 0) {
            UrlEncodedFormEntity entity = null;
            try {
                entity = new UrlEncodedFormEntity(list, CharEncoding.UTF_8);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            httpPost.setEntity(entity);
        }
        return getResponse(httpPost, CharEncoding.UTF_8, headers, ssl);
    }
    
    // 获取响应数据
    private static String getResponse(HttpRequestBase httpRequestBase, String charSet, Map<String, String> headers, boolean ssl) {
        CloseableHttpClient httpClient = null;
        try {
            httpClient = ssl ? getHttpClient() : HttpClients.createDefault();
            httpRequestBase.setConfig(getRequestConfig());
            if (headers.size() > 0) {
                httpRequestBase.setHeaders(getHeaders(headers));
            }
            CloseableHttpResponse response = httpClient.execute(httpRequestBase);
            int statusCode = response.getStatusLine().getStatusCode();
            if (HttpStatus.SC_OK == statusCode) {
                HttpEntity entity = response.getEntity();
                String res = EntityUtils.toString(entity, charSet);
                EntityUtils.consume(entity);
                return res;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (Objects.nonNull(httpClient)) {
                    httpClient.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        throw new RuntimeException("调用失败");
    }

    private static RequestConfig getRequestConfig() {
        return RequestConfig.custom().setConnectTimeout(6000 * 2).setConnectionRequestTimeout(6000 * 2).setSocketTimeout(6000 * 2).build();
    }

    private static String addParams(String url, Map<String, String> params) {
        return addParamsWithCharSet(url, params, CharEncoding.UTF_8);
    }

    private static String addParamsWithCharSet(String url, Map<String, String> params, String charSet) {
        if (params == null || params.isEmpty()) {
            return url;
        }
        StringBuilder sb = new StringBuilder();
        try {
            for (Map.Entry<String, String> entry : params.entrySet()) {
                sb.append("&").append(entry.getKey()).append("=");
                sb.append(charSet == null ? entry.getValue() : URLEncoder.encode(entry.getValue(), charSet));
            }
            if (!url.contains("?")) {
                sb.deleteCharAt(0).insert(0, "?");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return url + sb;
    }

   // HTTPS client 创建
    public static CloseableHttpClient getHttpClient() {
        X509TrustManager trustManager = new X509TrustManager() {
            @Override
            public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {}

            @Override
            public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {}

            @Override
            public X509Certificate[] getA***eptedIssuers() {
                return null;
            }
        };
        SSLContext context = null;
        try {
            context = SSLContext.getInstance("SSL");
            context.init(null, new TrustManager[]{trustManager}, null);
            return HttpClients.custom().setSSLSocketFactory(new SSLConnectionSocketFactory(context)).build();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage());
        }
    }

    // 设置请求头
    private static Header[] getHeaders(Map<String, String> header) {
        if (header.size() == 0) {
            return new Header[]{};
        }
        List<Header> headers = new ArrayList<>();
        for (String key : header.keySet()) {
            headers.add(new BasicHeader(key, header.get(key)));
        }
        return headers.toArray(new Header[]{});
    }

}

使用:

@RestController
@RequestMapping("/test")
public class TestController {

    @GetMapping("/queryById")
    public String queryById(String id) {
        Map<String, String> params = new HashMap<>();
        Map<String, String> headers = new HashMap<>();
        params.put("id", id);
        headers.put("X-A***ess-Token", "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE2ODcxNjM4MDcsInVzZXJuYW1lIjoibGlqaW5nIn0.BUeqjiBQrH0DCfciRQsWo1P1XOoIxXNuNaM27vjAmys");
        String url = "http://localhost:20001/test/queryById";
        return HttpClientUtil.get(url, params, headers, false);
    }

    @PostMapping("/add")
    public String add() {
        Map<String, String> headers = new HashMap<>();
        headers.put("X-A***ess-Token", "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE2ODcxNjM4MDcsInVzZXJuYW1lIjoibGlqaW5nIn0.BUeqjiBQrH0DCfciRQsWo1P1XOoIxXNuNaM27vjAmys");
        UserVo userVo = new UserVo();
        userVo.setId(1L);
        userVo.setName("zzc");
        String url = "http://localhost:20001/test/add";
        return HttpClientUtil.postJson(url, null, headers, JSON.toJSONString(userVo),false);
    }

}

2.OkHttp

<dependency>
	<groupId>***.squareup.okhttp3</groupId>
	<artifactId>okhttp</artifactId>
	<version>3.14.7</version>
</dependency>
public class OkHttpUtil {

    private static volatile OkHttpClient okHttpClient = null;
    private static volatile Semaphore semaphore = null;
    private Map<String, String> headerMap;
    private Map<String, Object> paramMap;
    private String url;
    private Request.Builder request;
    private String body;

    private OkHttpUtil() {
        if (Objects.isNull(okHttpClient)) {
            synchronized (OkHttpUtil.class) {
                if (Objects.isNull(okHttpClient)) {
                    TrustManager[] trustManagers = buildTrustManager();
                    okHttpClient = new OkHttpClient.Builder()
                            .connectTimeout(15, TimeUnit.SECONDS)
                            .writeTimeout(20, TimeUnit.SECONDS)
                            .readTimeout(20, TimeUnit.SECONDS)
                            .sslSocketFactory(createSSLSocketFactory(trustManagers), (X509TrustManager)trustManagers[0])
                            .hostnameVerifier((hostname, session) -> true)
                            .retryOnConnectionFailure(true)
                            .build();
                    addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36");
                }
            }
        }
    }

    public OkHttpUtil initGet() {
        request = new Request.Builder().get();
        StringBuilder builder = new StringBuilder(url);
        if (Objects.nonNull(paramMap)) {
            builder.append("?");
            paramMap.forEach((key, value) -> {
                try {
                    builder.append(URLEncoder.encode(key, "utf-8"))
                            .append("=")
                            .append(URLEncoder.encode((String)value, "utf-8"))
                            .append("&");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            });
            builder.deleteCharAt(builder.length() - 1);
        }
        request.url(builder.toString());
        return this;
    }

    public OkHttpUtil initPost(boolean isJson) {
        RequestBody requestBody = null;
        if (isJson) {
            requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), body);
        } else {
            FormBody.Builder formBody = new FormBody.Builder();
            if (Objects.nonNull(paramMap)) {
                paramMap.forEach((x, y) -> formBody.add(x, (String) y));
            }
            requestBody = formBody.build();
        }
        request = new Request.Builder().post(requestBody).url(url);
        return this;
    }

    /**
     * @Description:同步请求
     * @Author: zzc
     * @Date: 2022-12-04 18:06
     * @return: java.lang.String
     **/
    public String sync() {
        setHeader(request);
        try {
            Response result = okHttpClient.newCall(request.build()).execute();
            if (result.isSu***essful()) {
                return result.body().string();
            }
            throw new AiException(result.body().string());
        } catch (IOException e) {
            throw new AiException(e.getMessage());
        }
    }

    /**
     * @Description:异步请求,有返回值
     * @Author: zzc
     * @Date: 2022-12-04 18:05
     * @return: java.lang.String
     **/
    public String async() {
        StringBuffer buffer = new StringBuffer();
        setHeader(request);
        okHttpClient.newCall(request.build()).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                buffer.append("请求出错").append(e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (Objects.nonNull(response.body())) {
                    buffer.append(response.body().string());
                    getSemaphore().release();
                }
            }
        });
        try {
            getSemaphore().acquire();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return buffer.toString();
    }

    private static Semaphore getSemaphore() {
        synchronized (OkHttpUtil.class) {
            if (Objects.isNull(semaphore)) {
                semaphore = new Semaphore(0);
            }
        }
        return semaphore;
    }

    public static OkHttpUtil builder() {
        return new OkHttpUtil();
    }

    public OkHttpUtil url(String url) {
        this.url = url;
        return this;
    }

    public OkHttpUtil addParam(String key, String value) {
        if (Objects.isNull(paramMap)) {
            paramMap = new LinkedHashMap<>(16);
        }
        paramMap.put(key, value);
        return this;
    }

    public OkHttpUtil addBody(String body) {
        this.body = body;
        return this;
    }

    public void setHeader(Request.Builder request) {
        if (Objects.nonNull(headerMap)) {
            headerMap.forEach(request::addHeader);
        }
    }

    public OkHttpUtil addHeader(String key, String value) {
        if (Objects.isNull(headerMap)) {
            headerMap = new LinkedHashMap<>(16);
        }
        headerMap.put(key, value);
        return this;
    }

    /**
     * @Description:生成安全套接字工厂,用于Https请求的证书跳过
     * @Author: zzc
     * @Date: 2022-11-30 16:03
     * @param trustManagers:
     * @return: javax.***.ssl.SSLSocketFactory
     **/
    private static SSLSocketFactory createSSLSocketFactory(TrustManager[] trustManagers) {
        SSLSocketFactory sslSocketFactory = null;
        try {
            SSLContext ssl = SSLContext.getInstance("SSL");
            ssl.init(null, trustManagers, new SecureRandom());
            sslSocketFactory = ssl.getSocketFactory();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sslSocketFactory;
    }

    private static TrustManager[] buildTrustManager() {
        return new TrustManager[] {
                new X509TrustManager() {
                    @Override
                    public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {

                    }

                    @Override
                    public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {

                    }

                    @Override
                    public X509Certificate[] getA***eptedIssuers() {
                        return new X509Certificate[]{};
                    }
                }
        };
    }

}
public interface ICallback {
    void onSu***ess(Call call, String data);
    void onFail(Call call, String errorMsg);
}

使用:

@RestController
@RequestMapping("/ok")
public class OkHttpController {

    @GetMapping("/getByNoParams")
    public String getByNoParams() {
        String result = OkHttpUtil.builder().url("http://localhost:8080/http/listUsers")
                .initGet()
                .sync();
        System.out.println(result);
        return "get";
    }

    @GetMapping("/get")
    public String get() {
        String result = OkHttpUtil.builder().url("http://localhost:8080/http/getUserById")
                .addParam("id", "1")
                .initGet()
                .sync();
        System.out.println(result);
        return "get";
    }

    @GetMapping("/postByNoParams")
    public String postByNoParams() {
        String result = OkHttpUtil.builder().url("http://localhost:8080/http/listUserList")
                .initPost(false)
                .sync();
        System.out.println(result);
        return "post";
    }

    @GetMapping("/post")
    public String post() {
        String result = OkHttpUtil.builder().url("http://localhost:8080/http/getUserVoById")
                .addParam("id", "1")
                //.addHeader()
                .initPost(false)
                .sync();
        System.out.println(result);
        return "post";
    }

}

3.OKHttpUtil

在 Java 的世界中,Http 客户端之前一直是 Apache 家的 HttpClient 占据主导,但是由于此包较为庞大,API 又比较难用,因此并不使用很多场景。而新兴的 OkHttpJodd-http 固然好用,但是面对一些场景时,学习成本还是有一些的。针对 OKHttpOkHttpUtil 做了一层封装,使 Http 请求变得无比简单。

<dependency>
    <groupId>io.github.admin4j</groupId>
    <artifactId>http</artifactId>
    <version>0.4.0</version>
</dependency>
public class OkHttpUtil {

    public static JSONObject get(String url, Map<String, Object> queryParams) throws IOException {
        Response response = HttpUtil.get(url, queryParams);
        return JSONObject.parseObject(response.body().string());
    }
    
    public static JSONObject get(String url, Map<String, Object> queryParams, Map<String, Object> headers) throws IOException {
        HttpRequest httpRequest = HttpRequest.get(url);
        setParams(queryParams, httpRequest);
        Response response = httpRequest.queryParams().headers(headers).execute();
        return JSONObject.parseObject(response.body().string());
    }

    public static JSONObject post(String url, String json) throws IOException {
        Response response = HttpUtil.post(url, json);
        assert response.body() != null;
        return JSONObject.parseObject(response.body().string());
    }

    public static JSONObject postForm(String url, Map<String, Object> formParams) throws IOException {
        Response response = HttpUtil.postForm(url, formParams);
        assert response.body() != null;
        return JSONObject.parseObject(response.body().string());
    }

    public static JSONObject post(String url, String json, Map<String, Object> headers) throws IOException {
        HttpRequest httpRequest = HttpRequest.post(url);
        httpRequest.setBody(json);
        Response response = httpRequest.headers(headers).execute();
        return JSONObject.parseObject(response.body().string());
    }
    
    private static void setParams(Map<String, Object> queryParams, HttpRequest httpRequest) {
        List<Pair> pairs = new ArrayList<>(queryParams.size());
        queryParams.forEach((x, y) -> pairs.add(Pair.of(x, y)));
        if (pairs.size() > 0) {
            pairs.forEach(httpRequest::queryParams);
        }
    }
	
	private static JSONObject upload() throws IOException {
        File file = new File("C:\\Users\\andanyang\\Downloads\\Sql.txt");
        Map<String, Object> formParams = new HashMap<>();
        formParams.put("key", "test");
        formParams.put("file", file);
        formParams.put("token", "WXyUseb-D4sCum-EvTIDYL-mEehwDtrSBg-Zca7t:qgOcR2gUoKmxt-VnsNb657Oatzo=:eyJzY29wZSI6InpoYW56aGkiLCJkZWFkbGluZSI6MTY2NTMwNzUxNH0=");
        Response response = HttpUtil.upload("https://upload.qiniup.***/", formParams);
        return JSONObject.parseObject(response.body().string());
    }

    private static void download() throws IOException {
        HttpUtil.down("https://gitee.***/admin4j/***mon-http","path/");
    }

}

使用:

@RestController
@RequestMapping("/test")
public class TestController {

    @GetMapping("/queryById")
    public String queryById(String id) throws IOException {
        Map<String, Object> params = new HashMap<>();
        Map<String, Object> headers = new HashMap<>();
        params.put("id", id);
        headers.put("X-A***ess-Token", "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE2ODcyMjgxNjUsInVzZXJuYW1lIjoibGlqaW5nIn0.QNlQVrqiQymaeX38VXJCYhBXf3W6nQVDTmvlF0QKK-k");
        String url = "http://localhost:20001/test/queryById";
        OkHttpUtil.get(url, params, headers);
        return "get";
    }

    @PostMapping("/add")
    public String add() throws IOException {
        Map<String, String> headers = new HashMap<>();
        headers.put("X-A***ess-Token", "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE2ODcxNjM4MDcsInVzZXJuYW1lIjoibGlqaW5nIn0.BUeqjiBQrH0DCfciRQsWo1P1XOoIxXNuNaM27vjAmys");
        UserVo userVo = new UserVo();
        userVo.setId(1L);
        userVo.setName("zzc");
        String url = "http://localhost:20001/test/add";
        OkHttpUtil.post(url, JSON.toJSONString(userVo));
        return "post";
    }

    @PostMapping("/add2")
    public String add2() throws IOException {
        Map<String, Object> headers = new HashMap<>();
        headers.put("X-A***ess-Token", "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE2ODcyMzUzOTksInVzZXJuYW1lIjoibGlqaW5nIn0.zTOOhKS13RqWPj01fhWZoWR1Qz055uv2XG_eSIdt1NE");
        UserVo userVo = new UserVo();
        userVo.setId(1L);
        userVo.setName("zzc");
        String url = "http://localhost:20001/test/add";
        OkHttpUtil.post(url, JSON.toJSONString(userVo), headers);
        return "post";
    }

}

4.Jodd HTTP

<dependency>
    <groupId>org.jodd</groupId>
    <artifactId>jodd-http</artifactId>
    <version>6.3.0</version>
</dependency>
public class JoddUtil {

    public static JSONObject get(String url, Map<String, Object> queryParams) throws IOException {
        return get(url, queryParams, null);
    }

    public static JSONObject get(String url, Map<String, Object> queryParams, Map<String, String> headers) throws IOException {
        HttpRequest request = HttpRequest.get(url);
        setParams(request, queryParams);
        setHeaders(request, headers);
        return getResponse(request);
    }

    public static JSONObject post(String url, String json) throws IOException {
        return post(url, json, null);
    }

    public static JSONObject post(String url, String json, Map<String, String> headers) throws IOException {
        HttpRequest request = HttpRequest.post(url);
        request.contentType("application/json");
        request.charset("utf-8");
        setHeaders(request, headers);
        request.body(json);
        return getResponse(request);
    }

    public static JSONObject postForm(String url, Map<String, Object> formParams) throws IOException {
        return postForm(url, formParams, null);
    }

    public static JSONObject postForm(String url, Map<String, Object> formParams, Map<String, String> headers) throws IOException {
        HttpRequest request = HttpRequest.post(url);
        request.form(formParams);
        setHeaders(request, headers);
        return getResponse(request);
    }

    private static JSONObject getResponse(HttpRequest request) {
        HttpResponse response = request.send();
        response.charset("UTF-8");
        return JSONObject.parseObject(response.bodyText());
    }

    private static void setParams(HttpRequest request, Map<String, Object> queryParams) {
        if (Objects.nonNull(queryParams) && queryParams.size() > 0) {
            queryParams.forEach(request::query);
        }
    }
    
    private static void setHeaders(HttpRequest request, Map<String, String> headers) {
        if (Objects.nonNull(headers) && headers.size() > 0) {
            request.header(headers);
        }
    }

}

使用:

@RestController
@RequestMapping("/test")
public class TestController {

    @GetMapping("/queryById")
    public String queryById(String id) throws IOException {
        Map<String, Object> params = new HashMap<>();
        Map<String, String> headers = new HashMap<>();
        params.put("id", id);
        headers.put("X-A***ess-Token", "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE2ODcyNDQ2MjQsInVzZXJuYW1lIjoibGlqaW5nIn0.adNXSJnLDXBIRzcykM2Pkh1CF3R0So6D8FZ6w18PuXs");
        String url = "http://localhost:20001/test/queryById";
        JSONObject jsonObject = JoddUtil.get(url, params, headers);
        return "get";
    }

    @PostMapping("/add")
    public String add() throws IOException {
        Map<String, String> headers = new HashMap<>();
        headers.put("X-A***ess-Token", "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE2ODcyNDQ2MjQsInVzZXJuYW1lIjoibGlqaW5nIn0.adNXSJnLDXBIRzcykM2Pkh1CF3R0So6D8FZ6w18PuXs");
        UserVo userVo = new UserVo();
        userVo.setId(1L);
        userVo.setName("zzc");
        String url = "http://localhost:20001/test/add";
        JSONObject jsonObject = JoddUtil.post(url, JSON.toJSONString(userVo), headers);
        return "post";
    }

    @PostMapping("/add2")
    public String add2() throws IOException {
        Map<String, String> headers = new HashMap<>();
        Map<String, Object> formParams = new HashMap<>();
        headers.put("X-A***ess-Token", "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE2ODcyNDQ2MjQsInVzZXJuYW1lIjoibGlqaW5nIn0.adNXSJnLDXBIRzcykM2Pkh1CF3R0So6D8FZ6w18PuXs");
        formParams.put("id", 1631112733290594305L);
        String url = "http://localhost:20001/test/add2";
        JSONObject jsonObject = JoddUtil.postForm(url, formParams, headers);
        return "post";
    }

}

5.Hutool HTTP

Http客户端工具类-HttpUtil

<dependency>
    <groupId>***.hutool</groupId>
    <artifactId>hutool-all</artifactId>
    <version>5.8.6</version>
</dependency>
public class HutoolHttpUtil {

    public static JSONObject get(String url, Map<String, Object> queryParams) throws IOException {
        return get(url, queryParams, new HashMap<>(1));
    }

    public static JSONObject get(String url, Map<String, Object> queryParams, Map<String, String> headers) throws IOException {
        String body = HttpRequest.get(url).form(queryParams).addHeaders(headers).execute().body();
        return JSONObject.parseObject(body);
    }

    public static JSONObject post(String url, String json, Map<String, String> headers) {
        String body = HttpRequest.post(url).body(json).addHeaders(headers).execute().body();
        return JSONObject.parseObject(body);
    }
    
}

6.RestTemplate

@Configuration
public class RestTemplateConfig {

    @Bean
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }

}
@***ponent
public class RestTemplateUtil {

    @Autowired
    private RestTemplate restTemplate;

    public JSONObject get(String url, Map<String, Object> queryParams) throws IOException {
        return get(url, queryParams, new HashMap<>(1));
    }

    public JSONObject get(String url, Map<String, Object> queryParams, Map<String, String> headerParams) throws IOException {
        String tempUrl = setParamsByAppendUrl(queryParams, url);
        HttpHeaders headers = new HttpHeaders();
        headerParams.forEach(headers::add);
        HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<>(null, headers);
        ResponseEntity<String> response = restTemplate.exchange(tempUrl, HttpMethod.GET, httpEntity, String.class);
        return JSONObject.parseObject(response.getBody());
    }

    public JSONObject get2(String url, Map<String, Object> queryParams, Map<String, String> headerParams) throws IOException {
        String tempUrl = setParamsByPath(queryParams, url);
        HttpHeaders headers = new HttpHeaders();
        headerParams.forEach(headers::add);
        HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<>(null, headers);
        ResponseEntity<String> response = restTemplate.exchange(tempUrl, HttpMethod.GET, httpEntity, String.class, queryParams);
        return JSONObject.parseObject(response.getBody());
    }

    public JSONObject post(String url, String json, Map<String, String> headerParams) {
        HttpHeaders headers = new HttpHeaders();
        headerParams.forEach(headers::add);
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.add("A***ept", MediaType.APPLICATION_JSON.toString());
        HttpEntity<String> httpEntity = new HttpEntity<>(json, headers);
        ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, httpEntity, String.class);
        return JSONObject.parseObject(response.getBody());
    }

    private String setParamsByPath(Map<String, Object> queryParams, String url) {
        // url?id={id}&name={name}
        if (queryParams == null || queryParams.isEmpty()) {
            return url;
        }
        StringBuilder sb = new StringBuilder();
        try {
            for (Map.Entry<String, Object> entry : queryParams.entrySet()) {
                sb.append("&").append(entry.getKey()).append("=").append("{").append(entry.getKey()).append("}");
            }
            if (!url.contains("?")) {
                sb.deleteCharAt(0).insert(0, "?");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return url + sb;
    }

    private String setParamsByAppendUrl(Map<String, Object> queryParams, String url) {
        // url?id=1&name=zzc
        if (queryParams == null || queryParams.isEmpty()) {
            return url;
        }
        StringBuilder sb = new StringBuilder();
        try {
            for (Map.Entry<String, Object> entry : queryParams.entrySet()) {
                sb.append("&").append(entry.getKey()).append("=");
                sb.append(entry.getValue());
            }
            if (!url.contains("?")) {
                sb.deleteCharAt(0).insert(0, "?");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return url + sb;
    }

}

使用:

@RestController
@RequestMapping("/test")
public class TestController {

    @Autowired
    private RestTemplateUtil restTemplateUtil;

    @GetMapping("/queryById")
    public String queryById(String id) throws IOException {
        Map<String, Object> params = new HashMap<>();
        Map<String, String> headers = new HashMap<>();
        params.put("id", id);
        headers.put("X-A***ess-Token", "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE2ODczMTMxNTMsInVzZXJuYW1lIjoibGlqaW5nIn0.DStv6J23FcHRAWO5kvorfVHbao7Sih4nHPU-k4ynmeM");
        String url = "http://localhost:20001/test/queryById";
        JSONObject jsonObject = restTemplateUtil.get2(url, params, headers);
        return "get";
    }

    @PostMapping("/add")
    public String add() throws IOException {
        Map<String, String> headers = new HashMap<>();
        headers.put("X-A***ess-Token", "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE2ODczMTMxNTMsInVzZXJuYW1lIjoibGlqaW5nIn0.DStv6J23FcHRAWO5kvorfVHbao7Sih4nHPU-k4ynmeM");
        UserVo userVo = new UserVo();
        userVo.setId(1L);
        userVo.setName("zzc");
        String url = "http://localhost:20001/test/add";
        JSONObject jsonObject = restTemplateUtil.post(url, JSON.toJSONString(userVo), headers);
        return "post";
    }
}

7.forest

forest 官网

<dependency>
    <groupId>***.dtflys.forest</groupId>
    <artifactId>forest-spring-boot-starter</artifactId>
    <version>1.5.32</version>
</dependency>

配置:

forest:
  max-connections: 1000        # 连接池最大连接数
  connect-timeout: 3000        # 连接超时时间,单位为毫秒
  read-timeout: 3000           # 数据读取超时时间,单位为毫秒

扫描接口:

1.5.1以后版本可以跳过此步,不需要 @ForestScan 注解来指定扫描的包范围

只要在 Springboot 的配置类或者启动类上加上 @ForestScan 注解,并在 basePackages 属性里填上远程接口的所在的包名

public interface TestClient {

    @Get("http://localhost:20001/test/queryById")
    String queryById(@Header Map<String, Object> headerMap, @Query Map<String, Object> params);

    @Post("http://localhost:20001/test/add")
    String add(@Header Map<String, Object> headerMap, @JSONBody UserVo userVo);

}

测试:

@RestController
@RequestMapping("/forest")
public class ForestController {

    @Autowired
    private TestClient testClient;

    @GetMapping("/queryById")
    public String queryById(Long id) {
        Map<String, Object> headerMap = new HashMap<>();
        Map<String, Object> params = new HashMap<>();
        params.put("id", id);
        headerMap.put("X-A***ess-Token", "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE2ODg4MDg3NzQsInVzZXJuYW1lIjoiYWRtaW4ifQ.xo5h1KwdCvMkRpUf4SkioYSpyP7j3thA86vrdz7AcGY");
        return testClient.queryById(headerMap, params);
    }

    @PostMapping("/add")
    public String add(@RequestBody UserVo userVo) {
        Map<String, Object> headerMap = new HashMap<>();
        headerMap.put("X-A***ess-Token", "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE2ODg4MDg3NzQsInVzZXJuYW1lIjoiYWRtaW4ifQ.xo5h1KwdCvMkRpUf4SkioYSpyP7j3thA86vrdz7AcGY");
        return testClient.add(headerMap, userVo);
    }

}
转载请说明出处内容投诉
CSS教程_站长资源网 » 【SpringBoot】7 种实现 HTTP 调用的方式

发表评论

欢迎 访客 发表评论

一个令你着迷的主题!

查看演示 官网购买