用java发送get http请求
可以使用Java的HttpURLConnection类来发送GET请求。
以下是一个示例代码:
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("http://example.com/api/endpoint");
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());
}
}
}
在上面的示例代码中,我们使用HttpURLConnection类打开一个连接到指定的URL,并设置请求方式为GET。然后读取响应数据并将其存储在一个StringBuffer中。最后,我们打印出响应数据。
原文地址: https://www.cveoy.top/t/topic/4mu 著作权归作者所有。请勿转载和采集!