java - 尝试使用 RestTemplate 获取对象列表时响应正文为空

标签 java spring api resttemplate

所以我正在开发一个 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> responseResponseEntity<PoyntSubcriptionsList> responsePoyntSubcriptionsList代表您的 JSON。

关于java - 尝试使用 RestTemplate 获取对象列表时响应正文为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54884577/

相关文章:

java - 记录器不打印 spring mvc 中的堆栈跟踪

java - EditText On update/onChange value 添加监听器

java - 尝试以特定方式从 StringBuilder 中删除多个特定字符

java - 使用方向和轴旋转 3D 对象

java - ActiveMQ JNDI 查找问题

java - 为什么依赖注入(inject)需要另一种语言?

java - 验证 Spring Controller 参数不为空

java - LinkedIn 职位发布 API 在 Java 中的实现

java - 使用适用于 Android 的 Quizlet API

api - 与 postman 请求 SOAP