java http请求怎么设置编码类型为utf-8
时间: 2024-06-10 07:07:00 浏览: 260
你可以在请求头中设置编码类型为utf-8,具体方法如下:
```
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
public class HttpTest {
public static void main(String[] args) throws Exception {
String urlStr = "http://www.example.com";
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept-Charset", "utf-8");
conn.setDoOutput(true);
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8));
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
br.close();
}
}
```
在请求头中设置 "Accept-Charset" 为 "utf-8" 即可。
阅读全文