java实现http请求
时间: 2023-05-24 15:02:12 浏览: 68
可以使用Java内置的HttpURLConnection类来实现HTTP请求,也可以使用第三方库如Apache HttpClient来简化HTTP请求的处理。以下是使用HttpURLConnection实现GET请求的代码示例:
```java
URL url = new URL("http://example.com/"); // 请求的URL
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET"); // 请求方式为GET
conn.setRequestProperty("User-Agent", "Mozilla/5.0"); // 设置请求头
int responseCode = conn.getResponseCode(); // 获取请求返回码
if (responseCode == HttpURLConnection.HTTP_OK) { // 如果请求成功
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line = null;
while ((line = in.readLine()) != null) { // 读取响应数据
System.out.println(line);
}
in.close();
} else { // 否则抛出异常
throw new IOException("请求失败,返回码:" + responseCode);
}
```
其中,可以自行替换请求URL和设置请求头等信息,也可以使用POST请求、设置请求参数、上传文件等操作。