要使用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()
方法。