在Java中使用HttpURLConnection发送HTTP请求的步骤如下:
创建URL对象,指定要请求的URL地址。打开URL连接,使用openConnection()方法获取URLConnection对象。将URLConnection强制转换为HttpURLConnection对象,因为它是URLConnection的子类。设置请求方法,如GET、POST等,使用setRequestMethod()方法。设置请求头信息,如User-Agent、Content-Type等,使用setRequestProperty()方法。设置是否允许输入输出流,使用setDoInput()和setDoOutput()方法。发送请求,使用connect()方法。如果需要发送请求体,可以通过获取输出流,写入请求体数据。获取响应状态码,使用getResponseCode()方法。如果响应状态码为200,则表示请求成功,可以获取响应数据。获取响应输入流,使用getInputStream()方法。读取响应数据,可以使用BufferedReader等方式进行读取。关闭连接,使用disconnect()方法。下面是一个简单的示例代码:
import java.io.BufferedReader;import java.io.InputStreamReader;import java.net.HttpURLConnection;import java.net.URL;public class HttpURLConnectionExample { public static void main(String[] args) { try { // 创建URL对象 URL url = new URL("http://example.com"); // 打开URL连接 HttpURLConnection connection = (HttpURLConnection) url.openConnection(); // 设置请求方法 connection.setRequestMethod("GET"); // 设置请求头信息 connection.setRequestProperty("User-Agent", "Mozilla/5.0"); // 发送请求 connection.connect(); // 获取响应状态码 int statusCode = connection.getResponseCode(); // 判断是否请求成功 if (statusCode == HttpURLConnection.HTTP_OK) { // 获取响应输入流 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.toString()); } else { System.out.println("请求失败,状态码:" + statusCode); } // 关闭连接 connection.disconnect(); } catch (Exception e) { e.printStackTrace(); } }}注意:上述示例中的URL地址为示例,实际使用时需要替换为真实的URL地址。


