![](/img/trans.png)
[英]How to send body in restTemplate as application/x-www-form-urlencoded
[英]How to get and parse JSON response from x-www-form-urlencoded POST, RestTemplate (Java)?
我有這個方法來提出請求:
@Override
public HttpEntity<MultiValueMap<String, String>> generateRequestEntity(Date date) {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
map.add("key", "SOME_API_KEY");
map.add("source", "SOME_API_SOURCE");
if (date == null)
map.add("method", "getall");
else {
map.add("method", "getfrom");
map.add("date", new SimpleDateFormat("yyyy-MM-dd").format(date));
}
return new HttpEntity<>(map, headers);
}
我發送一個請求並得到一個響應,如以下鏈接所推薦的: URL
HttpEntity<MultiValueMap<String, String>> request = generateRequestEntity(date);
ResponseEntity<OnlineSell[]> response = restTemplate.postForEntity(url, request, OnlineSell[].class);
OnlineSell[] onlineSells = response.getBody();
但我有一個問題。 嘗試解析 JSON 響應時失敗。 OnlineSell - class,必須保留答案但我無法創建成功存儲此答案值的結構。 一個非常大而復雜的答案樹來了。
答:我可以從中獲取 JSONObject 以手動解析和保存嗎? 或者我可以通過之前更新這篇文章並添加它(回答表格 Postman )來獲得 JSON 解析的幫助嗎?
您可以做的是將 ResponseEntity 視為String
。 然后,您可以將objectMapper
與readValue()
一起使用,
像這樣的東西:
ResponseEntity<String> response = restTemplate().postForEntity(url, request, String.class);
String body = response.getBody();
OnlineSell[] onlineSells = new ObjectMapper().readValue(body, OnlineSell[].class);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.