【发布时间】:2019-02-26 11:32:14
【问题描述】:
所以我正在开发一个 REST 客户端,它使用一个 REST API 来使用 Spring RestTemplate 获取 json 对象列表。我正在使用 api 键设置必要的标题。所以我得到一个 HTTP 200 OK 响应,但响应正文是空的。当我使用 Postman 执行相同的请求时,它运行良好。这可能是什么原因?
代码sn-p:
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();
}
当 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;
}
}
PoyntSubscription 类:
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() {
}
【问题讨论】:
-
这个类 PoyntSubcriptionsList 是什么?请也发布 POJO
-
尝试使用这个 ResponseEntity
response = restTemplate.getForEntity(Url,PoyntSubcriptionsList.class); PoyntSubcriptionsList body = response.getBody(); -
@Dhanraj 它引发了一些转换错误
-
哎呀需要更改 void,现在试试这个 ResponseEntity
response = restTemplate.getForEntity(Url,PoyntSubcriptionsList.class); PoyntSubcriptionsList body = response.getBody(); -
在 PoyntSubcriptionsList 类中使用 @JsonGetter("list") 注释 getSubscriptions()
标签: java spring api resttemplate