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

这篇具有很好参考价值的文章主要介绍了【SpringBoot】7 种实现 HTTP 调用的方式。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

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

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

1. HttpClient

<dependency>
	<groupId>org.apache.httpcomponents</groupId>
	<artifactId>httpclient</artifactId>
	<version>4.5.6</version>
</dependency>
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 BasicNameValuePair(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[] getAcceptedIssuers() {
                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-Access-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-Access-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>com.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.isSuccessful()) {
                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.net.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[] getAcceptedIssuers() {
                        return new X509Certificate[]{};
                    }
                }
        };
    }

}
public interface ICallback {
    void onSuccess(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.com/", formParams);
        return JSONObject.parseObject(response.body().string());
    }

    private static void download() throws IOException {
        HttpUtil.down("https://gitee.com/admin4j/common-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-Access-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-Access-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-Access-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-Access-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-Access-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-Access-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>cn.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();
    }

}
@Component
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("Accept", 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-Access-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-Access-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>com.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);

}

测试:文章来源地址https://www.toymoban.com/news/detail-545170.html

@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-Access-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-Access-Token", "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE2ODg4MDg3NzQsInVzZXJuYW1lIjoiYWRtaW4ifQ.xo5h1KwdCvMkRpUf4SkioYSpyP7j3thA86vrdz7AcGY");
        return testClient.add(headerMap, userVo);
    }

}

到了这里,关于【SpringBoot】7 种实现 HTTP 调用的方式的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • SpringBoot 3.1 新版HTTP调用

    在SpringBoot3版本发布后 官方便声明了推荐使用了内置声明式的HTTP客户端。 一、声明式HTTP客户端使用(依赖引入) 二、被调用方编写(粗略代码逻辑) 三、调用方 HTTP端点编写 四、 工具类封装 五、调用地址定义常量   六、业务调用代码编写 七、调用接口 八、请求示例以及响应

    2024年02月12日
    浏览(39)
  • 互联网大厂技术-HTTP请求-Springboot整合Feign更优雅地实现Http服务调用 no suitable HttpMessageConverter found for response type

    目录 一、SpringBoot快速整合Feign 1.添加Pom依赖 2.启动类添加注解 3.引用Feign服务 二、为请求添加Header的3种方式 1.添加固定header 2.通过接口签名添加header 3.动态添加header 三、为请求添加超时配置 1.默认超时时间 3.超时异常 4.全局超时配置 5.为单个服务设置超时配置 四、为请求配

    2024年02月11日
    浏览(55)
  • Forest-声明式HTTP客户端框架-集成到SpringBoot实现调用第三方restful api并实现接口数据转换

    声明式HTTP客户端API框架,让Java发送HTTP/HTTPS请求不再难。它比OkHttp和HttpClient更高层, 是封装调用第三方restful api client接口的好帮手,是retrofit和feign之外另一个选择。 通过在接口上声明注解的方式配置HTTP请求接口。 官网: Forest   代码地址: forest: 声明式HTTP客户端API框架,让

    2024年02月04日
    浏览(115)
  • SpringBoot 项目中 对http调用异常处理

    spring 中 http调用 resp 会返回3个值 status/heard/body 分2种情况的异常 1.status 代表了通信异常, 也是我们常说的 http 状态码         只能是纯数字         200-成功, 404-不能访问的资源, 500-服务器异常         比较坑的是, 有些服务会, 把业务异常和这个进行合并, 或者篡改  2.bod

    2024年02月17日
    浏览(40)
  • Springboot调用http(https)接口小妙招,新手小白版

    有的新手彦祖在搬砖过程中会遇到调用别人接口来获取数据的需求,这其中涉及调用一些相关类及方法的调用,最近干活又要用这个了,把以前的代码搬出来套用下,死活报错协议加密证书啥的问题,真想感叹卑微打工仔挣点钱养家糊口不容易。无所谓,我师傅会出手,过来

    2024年02月13日
    浏览(61)
  • Springboot 获取http数据、打印HTTP参数的4种方式 (便于生产排查问题)

    Java的话本地打断点可以调试获取rest入参(http header),但是在生产环境可能我们获取入参(Http header/parameter)可能就没有那么的轻松了。我们可能在header中放置了很多自定的参数用来鉴权或者其他用途。如果排查问题的时候需要这些参数,我们有很多种选择去获取这些参数。

    2023年04月23日
    浏览(47)
  • Springboot -- 用更优雅的方式发HTTP请求(RestTemplate详解)

    RestTemplate 是 Spring 提供的用于访问Rest服务的客户端, RestTemplate 提供了多种便捷访问远程Http服务的方法,能够大大提高客户端的编写效率。 我之前的HTTP开发是用apache的HttpClient开发,代码复杂,还得操心资源回收等。代码很复杂,冗余代码多,稍微截个图,这是我封装好的一

    2024年02月02日
    浏览(40)
  • Springboot-Retrofit HTTP工具框架快速使用

    在SpringBoot项目直接使用okhttp、httpClient或者RestTemplate发起HTTP请求,既繁琐又不方便统一管理。 因此,在这里推荐一个适用于SpringBoot项目的轻量级HTTP客户端框架retrofit-spring-boot-starter,使用非常简单方便,同时又提供诸多功能增强 Retrofit是适用于Android和Java且类型安全的HTTP客户

    2024年02月13日
    浏览(49)
  • java实现调用http请求的几种常见方式

    ------ Oracle中文开发者社区 ------ 如果你想要学习编程,关注本博客,持续获得技术支持,持续获得技术咨询 java开发·企业官方账号 Oracle中国官方账号 Java中国管理部 全网粉丝30万+ 华为云享专家 阿里专家博主 CSDN内容合伙人 CSDN原力计划作者 51CTO专家博主 CSDN博客V账号 毕业于四川

    2024年02月04日
    浏览(56)
  • Java服务器调用Python服务器进行交互:基于Http协议的Restful风格调用(Springboot/FastApi)

    实现Java服务器调用Python服务器进行交互以及数据传输,可采用以下方法,亲测有效: 基于Restful风格进行请求调用: 框架 : Java服务器采用Springboot框架进行搭建服务 python服务器采用FastApi框架进行搭建服务 思路 :前端–Java–python–Java–前端 代码设计 :Axios-@PostMapping-请求

    2024年04月26日
    浏览(44)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包