springboot发起http请求
时间: 2023-10-12 16:01:01 浏览: 153
发送http请求
在Spring Boot中发起HTTP请求可以使用多种方式,以下是其中几种常用的方法:
1. 使用Java原生的URLConnection类进行请求:
```java
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 url = new URL("http://example.com");
// 打开连接
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// 设置请求方法
connection.setRequestMethod("GET");
// 发起请求并获取响应码
int responseCode = connection.getResponseCode();
// 读取响应内容
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
StringBuilder response = new StringBuilder();
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
// 输出结果
System.out.println("Response Code: " + responseCode);
System.out.println("Response Body: " + response.toString());
// 关闭连接
connection.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
2. 使用Spring的RestTemplate类进行请求:
```java
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
阅读全文