所以我正在开发一个 REST 客户端,它使用 REST API 来使用 Spring RestTemplate 获取 json 对象列表。我正在使用 api key 设置必要的 header 。所以我收到 HTTP 200 OK 响应,但响应正文为空。当我使用 postman 执行相同的请求时,效果很好。这可能是什么原因?
代码片段:
public List<PoyntSubscription> getSubscriptions(String apiToken, String cloudId, String cloudBaseUrl) {
List<PoyntSubscription> subscriptions = new ArrayList<>();
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.set("Api-Version", "1.2");
headers.set("Authorization", apiToken);
HttpEntity entity = new HttpEntity(headers);
ResponseEntity<PoyntSubscription> response = restTemplate.exchange(
cloudBaseUrl + cloudId + "/subscriptions?start=10", HttpMethod.GET, entity, PoyntSubcriptionsList.class);
return response.getBody().getSubscriptions();
}
当 postman 使用 API 时我得到的响应 json:
{
"list": [
{
"startAt": "2019-01-22T00:00:00Z",
"paymentStatus": "OVERDUE",
"createdAt": "2019-01-22T03:05:28Z",
"updatedAt": "2019-02-21T03:05:28Z",
"businessId": "xxxx",
"appId": "xxxx",
"subscriptionId": "xxxxx",
"phase": "FULL",
"planId": "xxxx",
"bundleId": "xxxx",
"planName": "xxxx",
"status": "ACTIVE"
}
],
"start": 10,
"total": 14,
"count": 4
}
PoyntSubscription 包装类:
public class PoyntSubcriptionsList {
private List<PoyntSubscription> subscriptions = new ArrayList();
public PoyntSubcriptionsList() {
}
public List<PoyntSubscription> getSubscriptions() {
return this.subscriptions;
}
public void setSubscriptions(List<PoyntSubscription> subscriptions) {
this.subscriptions = subscriptions;
}
}
Poynt订阅类:
public class PoyntSubscription {
private String startedDate;
private String paymentStatus;
private String createdDate;
private String updatedDate;
private String businessId;
private String appId;
private String subscriptionId;
private String phase;
private String planId;
private String bundleId;
private String planName;
private String status;
public PoyntSubscription() {
}
最佳答案
注释getSubscriptions()
与 @JsonGetter("list")
上课PoyntSubcriptionsList
.
您还需要更改ResponseEntity<PoyntSubscription> response
至ResponseEntity<PoyntSubcriptionsList> response
如PoyntSubcriptionsList
代表您的 JSON。
关于java - 尝试使用 RestTemplate 获取对象列表时响应正文为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54884577/