Avatar ·

如何在Java中发送HTTP请求?

大家好!请指教一下,如何在纯Java中正确执行HTTP请求(GET和POST),而不使用像Apache HttpClient或OkHttp这样的第三方库。我是Java新手,正在尝试理解网络请求。

我尝试使用java.net包中的HttpURLConnection类,但遇到了一些问题。以下是我的GET请求代码:

URL url = new URL("https://api.example.com/data");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(5000);
connection.setReadTimeout(5000);

int responseCode = connection.getResponseCode();
System.out.println("Response Code: " + responseCode);

BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
    response.append(inputLine);
}
in.close();