我想使用RestTemplate将POST请求发送到RestAPI。当我执行以下代码时,它给我的响应为空。但是,我的HTTP状态码为200 OK。 我已经正确添加了响应模型,因此模型没有问题。甚至,当我将响应类型更改为String时,它也没有响应。有什么建议吗?
MultiValueMap<String, String> headers = new LinkedMultiValueMap<String, String>();
headers.add("Authorization", "Basic " + "c21sOnBhc3N3b3Jk");
headers.add("Content-Type", "application/json");
RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
HttpEntity<NikeIdgenReq> request = new HttpEntity<NikeIdgenReq>(nikeIdgenReq, headers);
String resp = restTemplate.postForObject(url, request, String.class);
答案 0 :(得分:0)
在谷歌搜索之后,我找到了解决方案,使响应模型类可序列化 并在下面的代码中添加JsonProperty批注
public class NikeIdgenRes implements Serializable{
@JsonProperty("bundleID")
private String bundleID;
@JsonProperty("ids")
private List<Id> ids = null;
@JsonProperty("gtin")
private String gtin;
@JsonProperty("quantity")
private Integer quantity;
@JsonProperty("types")
private List<String> types = null;
@JsonProperty("meta")
private Meta meta;
// getters & setters
}
public NikeIdgenRes addNikeIdgen(NikeIdgenRq nikeIdgenRq) {
String url = "https://idgen-dev.connected-product.edflab.nikecloud.net/sensors/id_bundle/v1";
HttpEntity<NikeIdgenRq> httpEntity = new HttpEntity<>(nikeIdgenRq, getHttpHeaders());
ResponseEntity<NikeIdgenRes> result = restTemplateBuilder.build().postForEntity(url, httpEntity, NikeIdgenRes.class);
NikeIdgenRes nikeIdgenRes = new NikeIdgenRes();
nikeIdgenRes.setBundleID(result.getBody().getBundleID());
nikeIdgenRes.setIds(result.getBody().getIds());
nikeIdgenRes.setGtin(result.getBody().getGtin());
nikeIdgenRes.setQuantity(result.getBody().getQuantity());
nikeIdgenRes.setTypes(result.getBody().getTypes());
nikeIdgenRes.setMeta(result.getBody().getMeta());
return nikeIdgenRes;
}