在Java中,使用HttpURLConnection或HttpClient发送网络请求时,如果返回数据中存在中文乱码,可能是由于字符编码问题导致的。为了解决这个问题,需要在发送请求时设置正确的Header,以确保服务器能够正确地返回数据。

1. 使用HttpURLConnection发送请求:

URL url = new URL("http://example.com");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Accept-Charset", "UTF-8");
connection.setRequestProperty("User-Agent", "Mozilla/5.0");

int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
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();
connection.disconnect();
// 处理返回的数据
System.out.println(response.toString());
}

2. 使用HttpClient发送请求(需要导入Apache HttpClient库):

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

CloseableHttpClient httpClient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet("http://example.com");
httpGet.setHeader("Accept-Charset", "UTF-8");
httpGet.setHeader("User-Agent", "Mozilla/5.0");

HttpResponse response = httpClient.execute(httpGet);
HttpEntity entity = response.getEntity();
if (entity != null) {
String result = EntityUtils.toString(entity, "UTF-8");
// 处理返回的数据
System.out.println(result);
}
httpClient.close();

这些示例代码都会设置Accept-Charset为UTF-8,以确保正确处理中文字符。根据实际情况,你可能需要根据服务器的要求设置其他Header字段,如User-Agent等。

Java网络请求中文乱码解决方案:设置Header解决字符编码问题

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

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