Java GET 请求解决中文乱码问题
在 Java 中,使用 HttpURLConnection 或 HttpClient 发送 GET 请求时,需要设置字符编码为 UTF-8 来避免中文乱码问题。以下是一个示例代码:
使用 HttpURLConnection:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class Main {
public static void main(String[] args) {
try {
URL url = new URL('http://example.com');
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod('GET');
connection.setRequestProperty('Accept-Charset', 'UTF-8');
connection.connect();
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
InputStream inputStream = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, 'UTF-8'));
String line;
StringBuilder response = new StringBuilder();
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
System.out.println(response.toString());
}
connection.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}
使用 HttpClient:
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
public class Main {
public static void main(String[] args) {
HttpClient httpClient = HttpClientBuilder.create().build();
HttpGet httpGet = new HttpGet('http://example.com');
httpGet.setHeader('Accept-Charset', 'UTF-8');
try {
HttpResponse response = httpClient.execute(httpGet);
HttpEntity entity = response.getEntity();
String responseString = EntityUtils.toString(entity, 'UTF-8');
System.out.println(responseString);
} catch (IOException e) {
e.printStackTrace();
}
}
}
通过设置请求头和读取数据时的字符编码为 UTF-8,可以确保获取的数据以 UTF-8 编码解析,避免中文乱码问题。
原文地址: https://www.cveoy.top/t/topic/qt0G 著作权归作者所有。请勿转载和采集!