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

这篇具有很好参考价值的文章主要介绍了【SpringBoot】6 种实现 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-496092.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】6 种实现 HTTP 调用的方式的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

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

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

相关文章

  • 互联网大厂技术-HTTP请求-Springboot整合Feign更优雅地实现Http服务调用

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

    2024年02月04日
    浏览(58)
  • 【工作记录】基于springboot3+springsecurity6实现多种登录方式(一)

    springboot3已经推出有一段时间了,近期公司里面的小项目使用的都是springboot3版本的,安全框架还是以springsecurity为主,毕竟亲生的。 本文针对基于springboot3和springsecurity实现用户登录认证访问以及异常处理做个记录总结,也希望能帮助到需要的朋友。 需要提供登录接口,支持

    2024年03月24日
    浏览(50)
  • 【工作记录】基于springboot3+springsecurity实现多种方式登录及鉴权(二)

    上篇文章介绍了基于springboot3+springsecurity实现的基于模拟数据的用户多种方式登录及鉴权的流程和代码实现,本文我们继续完善。 主要通过如下几个点来完成优化和完善: 用户信息获取通过查询mysql数据库实现 token生成方式使用jwt 用户信息存储及读取使用redis 完善过滤器用户

    2024年01月19日
    浏览(42)
  • SpringBoot调用第三方WebService接口的两种实现方式

    WebService接口的发布通常一般都是使用WSDL(web service descriptive language)文件的样式来发布的,该文档包含了请求的参数信息,返回的结果信息,我们需要根据WSDL文档的信息来编写相关的代码进行调用WebService接口。接下来我将采用常见的两种方式调用WebService接口。 目前我需要

    2024年02月12日
    浏览(67)
  • SpringBoot集成websocket(3)|(websocket调用websocket采用回调方式实现数据互传)

    章节 第一章链接: SpringBoot集成websocket(1)|(websocket客户端实现) 第二章链接: SpringBoot集成websocket(2)|(websocket服务端实现以及websocket中转实现) 本节主要介绍的是springboot实现websocket的客户端服务端,以及客户端与服务端的数据互传。以下为伪代码,业务逻辑删除导致不

    2024年02月12日
    浏览(50)
  • Springboot3.X整合Dubbo3.XSpringCloudAlibaba微服务 2022.0 + Springboot3.X 集成 Dubbo实现对外调用http内部调用RPC

    近期自己新开了一套SpringCloud Alibaba微服务项目,接口使用了对外HTTP,内部RPC的设计,具体点说就是外部用户或客户端通过Nginx访问到Gateway网关再分发到各个服务,内部各个服务之间统一使用Dubbo RPC进行通信。下面是Springboot3.x集成Dubbo的分享: 1. 需要的关键依赖 2. 启动程序入

    2024年02月15日
    浏览(36)
  • 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日
    浏览(111)
  • 互联网大厂技术-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日
    浏览(53)
  • 微信小程序调用本地http接口设置以及django 遇到的csrf 403错误解决方法

    1) 如果微信小程序需要和本地localhost端口进行通信联调。首先需要设置微信小程序为 ”不校验合法域名…“设置,这样就可以跳过域名安全检测,不然会出现网站不在安全名单内: 2)此时调用之后,后端会出现如下错误: 这是因为:在微信小程序端对Django后台进行POST请求

    2024年02月07日
    浏览(56)
  • SAP ABAP调用Http/Https方式实例

    注意: 1.url必须带\\\"http://\\\"或者“https://”。 2. http_client-propertytype_redirect = http_client-co_disabled .这一行是设置是否允许重定向,是为“co_enabled”,否为“co_disabled”。 3. 可能出现的错误 404 Hostname Unknow,是因为服务器未配置该url的dns 4. 可能出现的错误 401 refused,可能是被防火墙

    2024年02月07日
    浏览(55)

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

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

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

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

二维码1

领取红包

二维码2

领红包