用java发送http get请求
时间: 2023-10-16 12:08:03 浏览: 86
java发送http get请求的两种方法(总结)
可以使用Java中的HttpURLConnection类来发送HTTP GET请求。以下是示例代码:
```java
import java.net.HttpURLConnection;
import java.net.URL;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class HttpGetExample {
public static void main(String[] args) {
try {
URL url = new URL("https://www.example.com/api/data");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
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());
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
}
}
```
这个示例代码会发送一个HTTP GET请求到`https://www.example.com/api/data`,并打印出响应的内容。
阅读全文