继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

RestTemplate使用指南

都要好好的ming
关注TA
已关注
手记 6
粉丝 0
获赞 0

RestTemplateConfig 配置类

 折叠原码

package com.pajk.bodhi.config; import org.apache.http.Header;import org.apache.http.client.HttpClient;import org.apache.http.client.config.RequestConfig;import org.apache.http.impl.client.DefaultConnectionKeepAliveStrategy;import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;import org.apache.http.impl.client.HttpClientBuilder;import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;import org.apache.http.message.BasicHeader;import org.slf4j.Logger;import org.slf4j.LoggerFactory;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.http.converter.HttpMessageConverter;import org.springframework.http.converter.StringHttpMessageConverter;import org.springframework.web.client.RestTemplate; import java.nio.charset.StandardCharsets;import java.util.ArrayList;import java.util.List;import java.util.concurrent.TimeUnit; @Configurationpublic class RestTemplateConfig {     private static final Logger LOGGER = LoggerFactory.getLogger(RestTemplateConfig.class);     @Bean    public RestTemplate restTemplate() {        // 添加内容转换器,使用默认的内容转换器        RestTemplate restTemplate = new RestTemplate(httpRequestFactory());        // 设置编码格式为UTF-8        List<HttpMessageConverter<?>> converterList = restTemplate.getMessageConverters();        HttpMessageConverter<?> converterTarget = null;        for (HttpMessageConverter<?> item : converterList) {            if (item.getClass() == StringHttpMessageConverter.class) {                converterTarget = item;                break;            }        }        if (converterTarget != null) {            converterList.remove(converterTarget);        }        HttpMessageConverter<?> converter = new StringHttpMessageConverter(StandardCharsets.UTF_8);        converterList.add(1,converter);         LOGGER.info("-----restTemplate-----初始化完成");        return restTemplate;    }     @Bean    public ClientHttpRequestFactory httpRequestFactory() {         return new HttpComponentsClientHttpRequestFactory(httpClient());     }     @Bean    public HttpClient httpClient() {        // 长连接保持30秒        PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(30, TimeUnit.SECONDS);        //设置整个连接池最大连接数 根据自己的场景决定        connectionManager.setMaxTotal(500);        //同路由的并发数,路由是对maxTotal的细分        connectionManager.setDefaultMaxPerRoute(500);         //requestConfig        RequestConfig requestConfig = RequestConfig.custom()                //服务器返回数据(response)的时间,超过该时间抛出read timeout                .setSocketTimeout(10000)                //连接上服务器(握手成功)的时间,超出该时间抛出connect timeout                .setConnectTimeout(5000)                //从连接池中获取连接的超时时间,超过该时间未拿到可用连接,会抛出org.apache.http.conn.ConnectionPoolTimeoutException: Timeout waiting for connection from pool                .setConnectionRequestTimeout(500)                .build();        //headers        List<Header> headers = new ArrayList<>();        headers.add(new BasicHeader("User-Agent""Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.16 Safari/537.36"));        headers.add(new BasicHeader("Accept-Encoding""gzip,deflate"));        headers.add(new BasicHeader("Accept-Language""zh-CN"));        headers.add(new BasicHeader("Connection""Keep-Alive"));        headers.add(new BasicHeader("Content-type""application/json;charset=UTF-8"));         return HttpClientBuilder.create()                .setDefaultRequestConfig(requestConfig)                .setConnectionManager(connectionManager)                .setDefaultHeaders(headers)                // 保持长连接配置,需要在头添加Keep-Alive                .setKeepAliveStrategy(new DefaultConnectionKeepAliveStrategy())                //重试次数,默认是3次,没有开启                .setRetryHandler(new DefaultHttpRequestRetryHandler(2true))                .build();    }    }

Http 客户端 请求工具

  • JDK HttpURLConnection

  • Apache HttpClient

  • OkHttp

RestTemplate 是一个同步的 Web Http 客户端请求模板工具,Spring框架做的抽象。使用时需要指定使用以上哪一种Http 客户端 。(后期会被废弃)

WebClient (后期推荐使用) 非阻塞 反应式 

 

HTTP协议状态码:

  • 1xx :通知请求可以继续请求

  • 2xx :请求成功

  • 3xx :重定向  301  永久迁移    302  临时迁移

  • 4xx :404 :访问url 不存在

  • 5xx :500 服务端错误

 


打开App,阅读手记
0人推荐
发表评论
随时随地看视频慕课网APP