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

Java实现UTF - 8编码的HTTP请求示例代码解析

下面是一个简单的Java程序,用于发送HTTP请求并指定UTF-8编码: ```java import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; public class HttpRequestExample { public static void main(String[] args) { try { // 创建URL对象 URL url = new URL("http://example.com"); // 创建连接对象 HttpURLConnection connection = (HttpURLConnection) url.openConnection(); // 设置请求方法为GET connection.setRequestMethod("GET"); // 设置请求头的编码为UTF-8 connection.setRequestProperty("Accept-Charset", "UTF-8"); // 发送请求 int responseCode = connection.getResponseCode(); // 读取响应 BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8")); StringBuilder response = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { response.append(line); } reader.close(); // 输出响应 System.out.println("Response Code: " + responseCode); System.out.println("Response: " + response.toString()); // 关闭连接 connection.disconnect(); } catch (Exception e) { e.printStackTrace(); } } } ``` 上面的代码使用Java的`HttpURLConnection`类发送HTTP GET请求,并设置请求头的编码为UTF-8。可以根据实际需求修改URL和请求方法等参数,并根据接口返回的数据类型解析响应结果。 ######[AI写代码神器 | 1549点数解答 | 2023-12-21 10:23:20]

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