处理爬取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;
    }
相关推荐
志尊宝10 分钟前
Vue3 零基础每日笔记(087):Vue3 高频面试题(下)
前端·javascript·vue.js·笔记·ecmascript·#vue.js
pusheng202540 分钟前
普晟传感再获“消防产业核心配套优质品牌”:以可靠传感技术,让全球合规变简单
大数据·前端·人工智能·物联网·安全
Java后端的Ai之路1 小时前
15_ReactJS_Flux_简介
前端·react.js·前端框架
‎ദ്ദിᵔ.˛.ᵔ₎1 小时前
Linux:对有关 SIGCHLD 的深层理解
linux·运维·服务器
定栓1 小时前
Webpack迁到Vite第五节:第三方库兼容
前端·webpack·node.js
aichitang20241 小时前
QCU 2.0.0:补齐 Windows、Linux 与 GNOME Wayland
linux·运维·windows·ai·agent·ai编程
Lv_沐曦1 小时前
Linux 上的Web文件管理器-filebrowser
linux·运维·服务器
NGINX开源社区1 小时前
与我们交流:NGINX Gateway Fabric 与 NGINX Ingress Controller 社区会议
java·服务器·前端
闲云自留地1 小时前
CentOS 搬 Ubuntu 24.04:yum 变 apt、防火墙、SELinux、root 全差异避坑
linux·ubuntu·centos