Java HTTP 请求:使用 HttpURLConnection 获取数据
使用 Java 通过 HTTP 获取数据的方式有很多,下面是一种常见的方式:
使用 Java 的 HttpURLConnection 类进行 HTTP 请求,示例代码如下:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpExample {
public static void main(String[] args) {
try {
URL url = new URL('http://example.com/api/data'); // 替换为实际的URL
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod('GET');
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
StringBuffer response = new StringBuffer();
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
System.out.println(response.toString());
} else {
System.out.println('HTTP request failed with response code: ' + responseCode);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
以上代码会向指定的 URL 发送 GET 请求,并将返回的数据打印在控制台上。你需要将示例代码中的 URL 替换为你实际要请求的 URL。
原文地址: https://www.cveoy.top/t/topic/qnQl 著作权归作者所有。请勿转载和采集!