resttemplate获取list
时间: 2023-10-18 17:32:04 浏览: 88
您可以使用`RestTemplate`来获取一个列表。以下是一个示例代码,演示如何使用`RestTemplate`来调用一个返回列表的REST API:
```java
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
public class RestClient {
public static void main(String[] args) {
// 创建一个RestTemplate对象
RestTemplate restTemplate = new RestTemplate();
// 发送GET请求,并将响应转换为List
ResponseEntity<List<YourObject>> response = restTemplate.exchange(
"https://api.example.com/your-api", // API的URL
HttpMethod.GET, // 请求方式
null, // 请求头信息
new ParameterizedTypeReference<List<YourObject>>() {} // 响应类型
);
// 从响应中获取列表
List<YourObject> yourList = response.getBody();
// 处理列表数据
for (YourObject object : yourList) {
System.out.println(object);
}
}
}
```
请注意,上述代码中的`YourObject`是您自己定义的类,它表示您所期望的列表中的对象类型。您需要根据实际情况进行相应的修改。
此外,请确保在您的项目中添加了适当的依赖,以便使用`RestTemplate`。对于Spring Boot项目,您可以在`pom.xml`文件中添加以下依赖:
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
```
希望这可以帮助到您!如果您有任何其他问题,请随时提问。
阅读全文
相关推荐


















