酷代码 AI
菜单
全部AI  /  热门  /  AI写代码神器
服务商

java模拟正常请求的header,用map帮我包装起来,httpurlconnection

可以按照以下方式使用Map来包装请求头,使用HttpURLConnection发送请求: ```java import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import java.util.HashMap; import java.util.Map; public class Main { public static void main(String[] args) { // 创建请求头Map Map<String, String> headers = new HashMap<>(); headers.put("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3"); headers.put("Content-Type", "application/json"); // 其他请求头字段... try { // 创建URL对象 URL url = new URL("http://example.com"); // 打开连接 HttpURLConnection connection = (HttpURLConnection) url.openConnection(); // 设置请求方法 connection.setRequestMethod("GET"); // 设置请求头 for (Map.Entry<String, String> entry : headers.entrySet()) { connection.setRequestProperty(entry.getKey(), entry.getValue()); } // 发送请求 int responseCode = connection.getResponseCode(); // 读取响应 BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line; StringBuilder response = new StringBuilder(); while ((line = reader.readLine()) != null) { response.append(line); } reader.close(); // 输出响应结果 System.out.println("Response Code: " + responseCode); System.out.println("Response Body: " + response.toString()); } catch (Exception e) { e.printStackTrace(); } } } ``` 在上述代码中,我们创建了一个`headers`的Map,其中包含了一些常见的请求头字段,你可以根据自己的需求添加或修改。然后使用`connection.setRequestProperty()`方法将这些请求头字段设置到`HttpURLConnection`对象中。最后发送请求并读取响应。 需要注意的是,这只是一个简单的示例,实际使用中可能还需要处理一些异常情况和请求参数。 [2024-08-26 18:00:13 | AI写代码神器 | 1449点数解答]

相关提问