RestTemplate传递json 设置application/json
RestTemplate
·
//post 请求 body传参数
private JSONObject post(String url, JSONObject params) {
LogerConstant.screenLog.info("[screen] 请求 " + url + " 参数 " + params.toString());
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity httpEntity = new HttpEntity<>(params.toString(), headers);
String body = restTemplate.postForObject(url, httpEntity, String.class);
LogerConstant.screenLog.info("[screen] 返回" + body);
JSONObject json = JSONObject.parseObject(body);
if (0 != json.getIntValue("code")) {
return null;
}
return json;
}
//get 请求 传参数
private JSONObject get(String url, MultiValueMap<String, Object> params) {
LogerConstant.screenLog.info("[screen] 请求 " + url + " 参数 " + params.toString());
String body = new RestTemplate().getForObject(url, String.class, params);
JSONObject json = JSONObject.parseObject(body);
LogerConstant.screenLog.info("[screen] 返回" + body);
if (0 != json.getIntValue("code")) {
return null;
}
return json;
}
//post body传json, header传参数
private JSONObject postBody(String url, String token, JSONArray jsonArray) {
LogerConstant.screenLog.info("[screen] 请求 " + url + " 参数 token:" + token + " json:" + jsonArray.toString());
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8);
httpHeaders.add("token", token);
HttpEntity<String> httpEntity = new HttpEntity<>(jsonArray.toString(), httpHeaders);
RestTemplate restTemplate = new RestTemplate();
String body = restTemplate.postForEntity(url, httpEntity, String.class).getBody();
JSONObject object = JSONObject.parseObject(body);
LogerConstant.screenLog.info("[screen] 返回" + body);
return object;
}
更多推荐
已为社区贡献1条内容
所有评论(0)