酷代码 AI
菜单
服务商
DeepSeek字节豆包讯飞星火
更多选项

Java实现UTF - 8编码HTTP请求示例及详细解析

以下是一个使用Java进行UTF-8编码的HTTP请求示例: ```java import java.net.HttpURLConnection; import java.net.URL; import java.io.OutputStream; public class HttpRequestExample { 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"); int responseCode = connection.getResponseCode(); System.out.println("Response Code: " + responseCode); if (responseCode == HttpURLConnection.HTTP_OK) { String response = new String(connection.getInputStream().readAllBytes(), "UTF-8"); System.out.println("Response: " + response); } } catch (Exception e) { e.printStackTrace(); } } } ``` 在这个示例中,我们使用`HttpURLConnection`类来发送一个GET请求到`http://example.com`。我们通过调用`setRequestProperty`方法来设置请求头中的`Accept-Charset`为`UTF-8`,以确保服务器以UTF-8编码响应。然后,我们使用`getInputStream`方法获取输入流,并使用`readAllBytes`方法读取所有字节。我们使用`new String`方法将字节数组转换为UTF-8编码的字符串。 ######[AI写代码神器 | 338点数解答 | 2023-12-21 10:25:23]

相关提问
本站限时免费提问中
实用工具查看更多
Linux在线手册 [开发类]
Jquery在线手册 [开发类]
今日油价 [生活类]
图片互转base64 [开发类]
时间转换器 [开发类]