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

 更新时间:2024年11月21日 11:34:45   作者:ReadyShowShow  
这篇文章主要介绍了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;
    }
}

到此这篇关于SpringBoot中restTemplate请求存在乱码问题的解决方法的文章就介绍到这了,更多相关SpringBoot restTemplate请求乱码内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • Java KeyStore文件生成方式

    Java KeyStore文件生成方式

    文章详解Java KeyStore生成参数及命令,指导如何用现有KeyStore创建TrustStore,并演示Tomcat中配置HTTPS连接器的步骤,包括密钥文件路径、密码设置及SSL协议配置,实现安全通信
    2025-09-09
  • 用java实现冒泡排序算法

    用java实现冒泡排序算法

    两两比较待排序记录的关键字,发现两个记录的次序相反时即进行交换,直到没有反序的记录为止
    2013-01-01
  • java编译后的文件出现xx$1.class的原因及解决方式

    java编译后的文件出现xx$1.class的原因及解决方式

    这篇文章主要介绍了java编译后的文件出现xx$1.class的原因及解决方式,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-12-12
  • JAVA版排序算法之快速排序示例

    JAVA版排序算法之快速排序示例

    这篇文章主要介绍了JAVA版排序算法之快速排序,结合实例形式分析了基于java版的遍历、递归实现快速排序功能的具体步骤与操作技巧,需要的朋友可以参考下
    2017-01-01
  • Maven的POM常用标签详解

    Maven的POM常用标签详解

    本文介绍maven中pom常用标签作用和用法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2025-09-09
  • IDEA控制台中文乱码的完整解决方案(小白也能轻松解决)

    IDEA控制台中文乱码的完整解决方案(小白也能轻松解决)

    在开发过程中,很多小伙伴会遇到这种情况,在 IntelliJ IDEA 的控制台里,本来是中文路径或日志,却显示成一堆 �������� 的乱码,别担心,今天我们就来手把手解决这个问题,需要的朋友可以参考下
    2025-09-09
  • 详细了解MVC+proxy

    详细了解MVC+proxy

    Java有两种代理方式,一种是静态代理,另一种是动态代理。对于静态代理,其实就是通过依赖注入,对对象进行封装,不让外部知道实现的细节。很多 API 就是通过这种形式来封装的
    2021-07-07
  • idea中怎样创建并运行第一个java程序

    idea中怎样创建并运行第一个java程序

    这篇文章主要介绍了idea中怎样创建并运行第一个java程序问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2023-08-08
  • Java使用文本块(Text Blocks)处理多行字符串的操作方法

    Java使用文本块(Text Blocks)处理多行字符串的操作方法

    本文介绍了Java文本块(TextBlocks)语法,它简化多行字符串的处理,保留文本格式、减少错误、提升代码可读性,本文详细解释了文本块的语法、缩进规则、常用转义符及常见使用场景,同时注意事项,需要的朋友可以参考下
    2026-05-05
  • Java使用设计模式中的工厂方法模式实例解析

    Java使用设计模式中的工厂方法模式实例解析

    当系统准备为用户提供某个类的子类的实例,又不想让用户代码和该子类形成耦合时,就可以使用工厂方法模式来设计系统.工厂方法模式的关键是在一个接口或抽象类中定义一个抽象方法,下面我们会具体介绍Java使用设计模式中的工厂方法模式实例解析.
    2016-05-05

最新评论