Java 使用Httpget发送请求设置哪些使用返回结果不乱码
在Java中使用Http.get()发送请求,可以通过设置请求头的Content-Type属性来指定返回结果的字符编码,从而避免乱码问题。常见的字符编码包括UTF-8、GBK等。
以下是设置Content-Type为UTF-8的示例代码:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpGetExample {
public static void main(String[] args) throws IOException {
URL url = new URL("https://example.com/api/endpoint");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
// 设置请求头的Content-Type属性为UTF-8
connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
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();
System.out.println("Response: " + response.toString());
} else {
System.out.println("HTTP GET request failed with response code: " + responseCode);
}
connection.disconnect();
}
}
在上述示例中,通过设置请求头的Content-Type属性为"application/json; charset=UTF-8"来指定返回结果的字符编码为UTF-8。在获取输入流时,使用InputStreamReader的构造函数指定字符编码为UTF-8,确保返回结果不乱码
原文地址: https://www.cveoy.top/t/topic/iNUl 著作权归作者所有。请勿转载和采集!