springboot之restTemplate的使用

一,创建RestTemplateConfig配置类


import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

@Configuration
public class RestTemplateConfig {

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

    @Bean
    public ClientHttpRequestFactory httpRequestFactory() {
        return new HttpComponentsClientHttpRequestFactory(httpClient());

    }

    @Bean
    public HttpClient httpClient() {
        Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("http", PlainConnectionSocketFactory.getSocketFactory())
                .register("https", SSLConnectionSocketFactory.getSocketFactory())
                .build();
        PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(registry);
        //设置整个连接池最大连接数 根据自己的场景决定
        connectionManager.setMaxTotal(200);
        //路由是对maxTotal的细分
        connectionManager.setDefaultMaxPerRoute(100);
        RequestConfig requestConfig = RequestConfig.custom()
                .setSocketTimeout(80000) //服务器返回数据(response)的时间,超过该时间抛出read timeout
                .setConnectTimeout(6000)//连接上服务器(握手成功)的时间,超出该时间抛出connect timeout
                .setConnectionRequestTimeout(2000)//从连接池中获取连接的超时时间,超过该时间未拿到可用连接,会抛出org.apache.http.conn.ConnectionPoolTimeoutException: Timeout waiting for connection from pool
                .build();
        return HttpClientBuilder.create()
                .setDefaultRequestConfig(requestConfig)
                .setConnectionManager(connectionManager)
                .build();
    }
}

二,创建HTTPTool类来发送请求

  • 向HTTPTool类中注入restTemplate
  • 调用restTemplate方法发送post和get请求
    完整代码如下:
@Component
public class HTTPTool {

    private static Logger logger = LoggerFactory.getLogger(HTTPTool.class);

    @Autowired
    private RestTemplate restTemplate;
    
    private static HTTPTool httpTool;

    @PostConstruct
    public void init() {
        httpTool = this;
    }
    /**
     * 发送POST请求
     *
     * @param url   URL
     * @param param 参数
     * @return POST请求的结果,Json格式
     */
    public static String postUrlForParam(String url, Map<String, Object> param) {
        HttpHeaders headers = new HttpHeaders();
        headers.add("Accept", MediaType.APPLICATION_JSON.toString());
        MediaType type = MediaType.parseMediaType("application/x-www-form-urlencoded; charset=UTF-8");
        headers.setContentType(type);
        MultiValueMap<String, Object> params = new LinkedMultiValueMap<>();
        if (param != null) {
            for (Map.Entry<String, Object> entry : param.entrySet()) {
                params.add(entry.getKey(), entry.getValue());
            }
        }
        HttpEntity<MultiValueMap<String, Object>> entity = new HttpEntity<>(params, headers);
        try {
            //获取响应的内容
            return httpTool.restTemplate.postForObject(url, entity, String.class);
        } catch (Exception e) {
            logger.error("postUrlForParam error e:{}", e.getMessage());
            return null;
        }
    }

	/**
     * @param baseUrl       提交的URL
     * @return 提交响应
     */
    public static String getUrlForParam(String baseUrl, Map<String, Object> params) throws RuntimeException {
        HttpHeaders headers = new HttpHeaders();
        headers.set("Accept", MediaType.APPLICATION_JSON.toString());
        HttpEntity entity = new HttpEntity(headers);
        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
        headers.setContentType(type);
        try {
            ResponseEntity<String> exchange = httpTool.restTemplate.exchange(baseUrl, HttpMethod.GET, entity, String.class, params);
            return exchange.getBody();
        } catch (RestClientException e) {
            logger.error("postUrlForParam error e:{}", e.getMessage());
            return null;
        }
    }

注意:如果是get请求,又想要把参数封装到map里面进行传递的话,Map需要使用HashMap,且url需要使用占位符,请求示例如下:

		String url = "http://localhost:8080/person/find?id={id}";
        Map<String, Object> map = new HashMap<>();
        map.put("id", personId);
        //调用get请求方法
        getUrlForParam(url, map);

参考博客:
https://my.oschina.net/sdlvzg/blog/1800395
https://blog.csdn.net/LDY1016/article/details/80002126

你可能感兴趣的:(springboot)