一种简单(即缺少异常处理等)的方式如下:
首先,您需要一个类来表示您正在接收的数据,其字段与 API 响应字段匹配,例如:
public class Article {
private String source;
private String title;
... // more fields
// getters and setters
}
从 API 获取数据的代码如下所示:
RestTemplate template = ... // initialized earlier
ResponseEntity<Article[]> response = template.exchange(
API_URL, // url to the api
HttpMethod.GET, // use the Http verb "GET"
new HttpEntity<>(headers), // optional headers, e.g. for basic auth
Article[].class // the expected response type is Article[]
);
Article[] articles = response.getBody();
List<Article> list = Arrays.asList(articles); // if you need to use collections
注意,ResponseEntity 为非 null 并不意味着请求成功。您可以使用responseEntity.getStatusCode() 来确定响应的状态码。
但是要小心,因为默认情况下,RestTemplate 在收到非 200 错误代码时会引发异常(HttpClientErrorException 和 HttpServerErrorException 分别用于 4XX 和 5XX 代码)。如果您想要自己的自定义错误处理,您应该调用:
template.setErrorHandler(new ResponseErrorHandler() {
@Override
public boolean hasError(ClientHttpResponse response) throws IOException {
// implement here
}
@Override
public void handleError(ClientHttpResponse response) throws IOException {
// implement here
}
});
对于 MongoDB 的持久性,您可以使用 JPA,尽管由于 JPA 固有的关系性质与 Mongo 的非关系结构发生冲突,因此 JPA 并不适合 MongoDB。像 Spring Data 这样的东西可以更明智地映射这一点,值得研究:https://spring.io/projects/spring-data-mongodb
编辑 - 调用此代码
通常,我将创建一个带有实现的类/接口(例如称为ArticleResource),如下所示:
public class ArticleResource {
private final RestTemplate template = new RestTemplate();
public List<Article> getAllArticles() {
ResponseEntity<Article[]> response = template.exchange(API_URL, HttpMethod.GET, new HttpEntity<>(headers), Article[].class);
// some error checking here
return response.getBody() == null ? Collections.emptyList() : Arrays.asList(response.getBody());
}
}
对于需要单个值的方法(例如 findArticleByTitle(String title)),我通常会返回 Optional<Article>(返回 Optional<List<T>> 是不好的做法,因为空列表已经表示“没有值”)。
您可以在代码中调用:
ArticleResource resource = new ArticeResource();
// if you want to print all the names for example:
resource.getAllArticles().stream().map(Article::getName).forEach(System.out::println);