Java 后台发送请求
时间: 2024-09-21 13:04:00 浏览: 41
在Java后台(通常指服务器端)发送HTTP请求,可以使用多种库来处理,其中最常用的是`java.net`包下的`HttpURLConnection`或更现代的第三方库如`Apache HttpClient`、`OkHttp`或`Spring Web Client`。
1. 使用`HttpURLConnection`:
```java
URL url = new URL("http://example.com/api");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET"); // 或POST、PUT等
connection.setDoOutput(true); // 如果有数据需要发送
try (BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
System.out.println(response.toString());
}
// 关闭连接
connection.disconnect();
```
2. 使用`Apache HttpClient`:
```java
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet("http://example.com/api");
try {
HttpResponse response = httpClient.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
System.out.println(response.getStatusLine().toString());
try (BufferedReader in = new BufferedReader(
new InputStreamReader(response.getEntity().getContent()))) {
String inputLine;
StringBuffer content = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
content.append(inputLine);
}
System.out.println(content.toString());
} finally {
response.close();
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
httpClient.close();
}
```
3. 使用`Spring WebClient` (Spring Boot项目):
```java
RestTemplate restTemplate = new RestTemplate(); // 如果配置了Spring自动注入,则不需要创建
ResponseEntity<String> response = restTemplate.getForEntity("http://example.com/api", String.class);
String responseBody = response.getBody();
System.out.println(responseBody);
```
阅读全文
相关推荐
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)