使用Java发送HttpGet请求的步骤如下:
- 导入所需的类:
import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL;
- 创建URL对象,指定要发送请求的URL:
URL url = new URL("http://example.com");
- 打开连接并创建HttpURLConnection对象:
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
- 设置请求方法为GET:
connection.setRequestMethod("GET");
- 获取响应码:
int responseCode = connection.getResponseCode();
- 根据响应码判断请求是否成功:
if (responseCode == HttpURLConnection.HTTP_OK) { 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()); } else { System.out.println("请求失败"); }
- 关闭连接:
connection.disconnect();
完整的示例代码如下:
import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; public class HttpGetExample { public static void main(String[] args) { try { URL url = new URL("http://example.com"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); int responseCode = connection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { 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()); } else { System.out.println("请求失败"); } connection.disconnect(); } catch (Exception e) { e.printStackTrace(); } } }
注意:上述示例代码中的URL为示例URL,实际使用时需要替换为你要发送请求的URL。