RestTemplate使用

1.获取http头对象

// org.springframework.http.HttpHeaders
private HttpHeaders getHttpHeaders() {
        HttpHeaders headers = new HttpHeaders();
        headers.setAcceptCharset(Collections.singletonList(Charset.forName("UTF-8")));
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("X-Auth-Token", "2Rgoes5JO/kxOHYgkpQ25w==");
        return headers;
    }

2.生成查询参数

private HttpEntity<Map<String, Object>> getHttpRequestParams(HttpHeaders headers){
      //转发请求参数
      Map<String, Object> params = new HashMap<>();
       params.put("src", new String[]{"th", "yn", "cap", "lf", "hc"});
       HttpEntity<Map<String, Object>> requestParam = new HttpEntity<>(params, headers);
      return requestParam;
}

3.发送http请求

RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = getHttpHeaders();
HttpEntity<Map<String, Object>> requestParam = getHttpRequestParams(headers);
ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, requestParam, String.class);
JSONObject resJson = JSON.parseObject(responseEntity.getBody(), JSONObject.class);
            

4.使用支持http的get请求提交body的restemplate,通知内部工具类使用httpclient

package com.xxx.jscaffold.config;

import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.HttpClientBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.RestTemplate;

import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;

@Configuration
public class RestTemplateConfig {

    /**
     * 兼容http的get请求来发送body的功能
     */
    static class HttpComponentsClientRestfulHttpRequestFactory extends HttpComponentsClientHttpRequestFactory {
        @Override

        protected HttpUriRequest createHttpUriRequest(HttpMethod httpMethod, URI uri) {

            if (httpMethod == HttpMethod.GET) {
                return new HttpGetRequestWithEntity(uri);
            }

            return super.createHttpUriRequest(httpMethod, uri);

        }

        /**
         * 定义HttpGetRequestWithEntity实现HttpEntityEnclosingRequestBase抽象类,以支持GET请求携带body数据
         */

        private static final class HttpGetRequestWithEntity extends HttpEntityEnclosingRequestBase {

            public HttpGetRequestWithEntity(final URI uri) {
                super.setURI(uri);
            }
            @Override

            public String getMethod() {
                return HttpMethod.GET.name();
            }

        }
    }

    @Bean
    public RestTemplate restTemplate() {

        // 设置超时时间,单位为毫秒
        int connectionTimeout = 5000; // 连接超时设置为 5 秒
        int socketTimeout = 20000; // 读取超时设置为 10 秒

        HttpClient httpClient = HttpClientBuilder.create()
                .setConnectionTimeToLive(connectionTimeout, TimeUnit.MILLISECONDS)
                .setDefaultRequestConfig(RequestConfig.custom()
                        .setConnectTimeout(connectionTimeout)
                        .setSocketTimeout(socketTimeout)
                        .build())
                .build();

// 将自定义的 HttpClient 实例设置到 HttpComponentsClientHttpRequestFactory 中
        HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientRestfulHttpRequestFactory();
        requestFactory.setHttpClient(httpClient);


        RestTemplate restTemplate = new RestTemplate(requestFactory);
        restTemplate.getMessageConverters()
                .add(0, new StringHttpMessageConverter(StandardCharsets.UTF_8));
        return restTemplate;
    }
}

posted @ 2021-01-05 11:16  SpecialSpeculator  阅读(185)  评论(0编辑  收藏  举报