在Java中,处理网络请求中的中文乱码可以通过设置HTTP请求头的编码格式来解决。

以下是一个示例代码:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class Main {

    public static void main(String[] args) throws IOException {
        String url = "http://example.com"; // 替换为你的请求URL

        HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
        connection.setRequestMethod("GET");
        connection.setRequestProperty("Accept", "application/json;charset=UTF-8"); // 设置请求头的编码格式

        BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
        String line;
        StringBuilder response = new StringBuilder();
        while ((line = reader.readLine()) != null) {
            response.append(line);
        }
        reader.close();

        System.out.println(response.toString());
    }
}

在上述代码中,通过设置connection.setRequestProperty("Accept", "application/json;charset=UTF-8")来指定HTTP请求头的编码格式为UTF-8。然后,通过new InputStreamReader(connection.getInputStream(), "UTF-8")来指定输入流的编码格式为UTF-8,保证读取的中文内容不会乱码。

注意:在实际使用中,需要根据实际情况调整编码格式,例如,如果服务端返回的数据编码方式为GBK,则需要将编码格式设置为GBK

Java Get网络请求中文乱码

原文地址: https://www.cveoy.top/t/topic/iNNt 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录