【发布时间】:2019-10-24 16:35:51
【问题描述】:
我想以易于阅读的格式在浏览器中打印来自 RESTful 请求的 json 响应,同时保留 json 的换行符和缩进。
我当前的代码将 json 响应保存在一个字符串中,并在没有任何格式的情况下打印该字符串。
在 RESTFulController.java 中
@Controller
public class RESTFulControllerController {
@RequestMapping("myrequest")
public String myRequest(Model model) {
//--> Initializations
RestTemplate rest_template= new RestTemplate();
String url = "https://example.com/api";
//--> Create http request
HttpHeaders headers = new HttpHeaders();
MultiValueMap<String, String> body_map = new LinkedMultiValueMap<>();
body_map.add("resource_id", "value_of_resource_id");
HttpEntity<MultiValueMap<String, String>> request_entity = new HttpEntity<>(body_map, headers);
//--> Post http request
String response = rest_template.postForObject(url, request_entity, String.class);
//--> Add data for display
model.addAttribute("response", response);
return "print_response";
}
在模板/print_response.html中
<body>
[[${response}]]
</body>
不需要进一步处理响应,它将仅用于在浏览器中的可视化。在控制器或模板中进行格式化更好吗?以及如何?
提前致谢!
【问题讨论】:
标签: json spring-boot thymeleaf