SpringBoot中的restTemplate请求存在乱码问题的解决

SpringBoot中的restTemplate请求存在乱码问题的解决

在这里插入图片描述

搜索网上各种解法,最后在不断的一点点对比中,排查到了问题,是restTemplate不支持gzip,对返回的数据不能对gzip自动解压,因此需要去掉header中的accept-encoding
在这里插入图片描述

网上提到的另一种解决方式是配置

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.springframework.http.HttpHeaders;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

@Configuration
public class RestTemplateConfig {

    @Bean
    public RestTemplate restTemplate() {
        // 创建 HttpClient
        CloseableHttpClient httpClient = HttpClients.custom()
                .setConnectionManager(new PoolingHttpClientConnectionManager())
                .build();

        // 配置 RequestFactory
        HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient);
        RestTemplate restTemplate = new RestTemplate(requestFactory);

        // 添加请求头,告知服务器支持 Gzip
        restTemplate.getInterceptors().add((request, body, execution) -> {
            request.getHeaders().add(HttpHeaders.ACCEPT_ENCODING, "gzip, deflate, br");
            return execution.execute(request, body);
        });
        return restTemplate;
    }
}

而实际运行时还是会报错的。
一个解决方案就是 headers.remove(HttpHeaders.ACCEPT_ENCODING),但是并不完美。

    @GetMapping("/**")
    public ResponseEntity<String> proxyGetRequest(@RequestHeader HttpHeaders headers, HttpServletRequest request) {
        String requestUri = request.getRequestURI().replace("/proxy", "");
        String targetUrl = "https://pre-youku-prefect-v2.alibaba-inc.com" + requestUri;

        headers.remove(HttpHeaders.ACCEPT_ENCODING); //必须去掉gzip压缩
        ResponseEntity<String> response = restTemplate.exchange(targetUrl, HttpMethod.GET, new HttpEntity<>(headers), String.class);
        return ResponseEntity.status(response.getStatusCode()).body(response.getBody());
    }

最终原因

再深入分析后,发现实现代理时,应返回字节流,而不能是字符流,就能完美的实现代理功能

@RestController
@RequestMapping("/proxy")
public class ProxyController {

    private final RestTemplate restTemplate;

    public ProxyController(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    @GetMapping("/**")
    public ResponseEntity<byte[]> proxyGetRequest(@RequestHeader HttpHeaders headers, HttpServletRequest request) {
        String requestUri = request.getRequestURI().replace("/proxy", "");
        String targetUrl = "https://xxx.com" + requestUri;
        ResponseEntity<byte[]> response = restTemplate.exchange(targetUrl, HttpMethod.GET, new HttpEntity<>(headers), byte[].class);
        return response;
    }

    @PostMapping("/**")
    public ResponseEntity<byte[]> proxyPostRequest(@RequestHeader HttpHeaders headers, @RequestBody String body, HttpServletRequest request) {
        String requestUri = request.getRequestURI().replace("/proxy", "");
        String targetUrl = "https://xxx.com" + requestUri;
        ResponseEntity<byte[]> response = restTemplate.exchange(targetUrl, HttpMethod.POST, new HttpEntity<>(body, headers), byte[].class);
        return response;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值