如何使用Java发送HTTP请求并获取URL响应

   2024-09-30 9780
核心提示:要使用Java发送HTTP请求并获取URL响应,可以使用java.net.HttpURLConnection类import java.io.BufferedReader;import java.io.In

要使用Java发送HTTP请求并获取URL响应,可以使用java.net.HttpURLConnection类

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("https://api.example.com/data");            // 打开连接            HttpURLConnection connection = (HttpURLConnection) url.openConnection();            // 设置请求方法(GET或POST)            connection.setRequestMethod("GET");            // 设置请求头(可选)            connection.setRequestProperty("User-Agent", "Mozilla/5.0");            // 获取响应码            int responseCode = connection.getResponseCode();            System.out.println("Response Code: " + responseCode);            // 读取响应内容            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));            String inputLine;            StringBuilder response = new StringBuilder();            while ((inputLine = in.readLine()) != null) {                response.append(inputLine);            }            // 关闭输入流            in.close();            // 输出响应内容            System.out.println(response.toString());        } catch (Exception e) {            e.printStackTrace();        }    }}

这个示例向https://api.example.com/data发送一个GET请求,然后读取并输出响应内容。你可以根据需要修改URL、请求方法和请求头。如果你需要发送POST请求并提交数据,可以使用connection.setDoOutput(true)和connection.getOutputStream()方法。

 
举报打赏
 
更多>同类物流大全
推荐图文
推荐物流大全
点击排行

网站首页  |  关于我们  |  联系方式 | 网站留言    |  赣ICP备2021007278号