Java写一个网络请求的代码
时间: 2024-04-28 12:21:18 浏览: 7
在 Java 中,可以使用 `java.net` 包下的类来进行网络请求。下面是一个简单的网络请求示例:
```
import java.net.*;
import java.io.*;
public class HttpUrlConnectionExample {
public static void main(String[] args) {
try {
URL url = new URL("https://www.example.com/api/data"); // 请求的 URL
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET"); // 请求方法为 GET
conn.setRequestProperty("Accept", "application/json"); // 设置请求头
conn.setConnectTimeout(5000); // 设置连接超时时间
conn.setReadTimeout(5000); // 设置读取超时时间
int responseCode = conn.getResponseCode(); // 获取响应码
System.out.println("Response Code : " + responseCode);
if (responseCode == HttpURLConnection.HTTP_OK) { // 如果响应码为 200
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
System.out.println(response.toString()); // 输出响应结果
} else {
System.out.println("GET request not worked");
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
```
以上代码使用 `HttpURLConnection` 类来发送 GET 请求,并获取响应结果。我们可以通过设置请求头,连接超时时间,读取超时时间等来进行自定义配置。其中,`getResponseCode()` 方法可以获取响应码,如果响应码为 200,则表示请求成功。最后,我们可以通过 `getInputStream()` 方法获取响应结果的输入流,使用 `BufferedReader` 读取输入流中的数据,最后将数据输出即可。