处理爬取html内容调用RestTemplate方法远程调接口会出现中文乱码问题

问题如图

处理代码如下

java 复制代码
 RestTemplate restTemplate = new RestTemplate();
            String url1 = SystemParam.getValue("interface");
            System.out.println("htmlContent----"+htmlContent);
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            HttpEntity<String> requestEntity = new HttpEntity<>(json, headers);
            String result = restTemplate.postForObject(url1, requestEntity, String.class);

相当于加上

java 复制代码
 HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            HttpEntity<String> requestEntity = new HttpEntity<>(json, headers);

使用 HttpEntity 来发送请求实体,可以使用 HttpEntity 将 JSON 字符串发送到服务端,并且确保字符集为 UTF-8

以下为处理html模板页内容

java 复制代码
public static String fetchTemplateHtml(String reporturl, String siteid, String nowDate) {
        String templateHtml = null;
        CloseableHttpClient httpClient = HttpClients.createDefault();
        try {
            String url = 填写所要获取的地址接口,跳转html的接口以及接口内要有数据;下面就是处理解析数据然后放到对应的获取参数的位置,我这里处理的是不是通过ajax获取的参数,是通过原生,后端给前端通过model.addAttribute传递参数
            HttpGet httpGet = new HttpGet(url);
            httpGet.setHeader("Accept-Encoding", "UTF-8");
            httpGet.setHeader("Content-Type", "application/json; charset=UTF-8");
            CloseableHttpResponse response = httpClient.execute(httpGet);
            if (response.getStatusLine().getStatusCode() == 200) {
                templateHtml = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return templateHtml;
    }
相关推荐
Bert.Cai7 小时前
Linux let命令详解
linux·运维·服务器
枕星而眠7 小时前
Linux 线程:原理、属性、实战与面试避坑
linux·运维·c语言·面试
晚风予卿云月7 小时前
【Linux】环境变量概念、作用、配置与修改详解
linux·运维·服务器·环境变量
r-t-H7 小时前
从零开始搭建CDH-第十二章
linux·hive·spark·centos·hbase
~黄夫人~7 小时前
零基础速通|Windows&Linux 常用命令行对照表大全
linux·运维·windows·笔记·备忘录·整理表格
benjiangliu7 小时前
LINUX系统-17-EXT系列文件系统(二)
linux·运维·服务器
杨云龙UP7 小时前
Linux 根分区被日志吃满?一次 58G Broker 日志清理实战_2026-05-20
linux·运维·服务器·数据库·hdfs·apache
叶半欲缺8 小时前
Linux通过lvm扩容根目录
linux·运维·服务器
发现一只大呆瓜8 小时前
超全 Vite 性能优化指南:网络、资源、预渲染三维落地方案
前端·面试·vite
utf8mb4安全女神8 小时前
Linux网络服务
linux·运维·服务器