java发送get请求
时间: 2023-07-19 19:46:18 浏览: 37
可以使用 Java 中的 HttpURLConnection 类来发送 GET 请求。
以下是一个简单的示例:
```
import java.net.HttpURLConnection;
import java.net.URL;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class HttpGetRequest {
public static void main(String[] args) throws Exception {
String url = "http://example.com/api/data"; //待请求的 URL
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
//设置请求方法为 GET
con.setRequestMethod("GET");
//获取响应状态码
int responseCode = con.getResponseCode();
System.out.println("Response Code : " + responseCode);
//读取响应内容
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
//打印响应内容
System.out.println(response.toString());
}
}
```
在上述示例中,我们使用 HttpURLConnection 类创建了一个 GET 请求并获取了响应内容。你只需要将 URL 替换成你要请求的 URL,即可使用该示例发送 GET 请求。