package com.example.demo.utils; import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.parser.Feature; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.ResponseEntity; import org.springframework.web.client.HttpClientErrorException; import org.springframework.web.client.HttpServerErrorException; import org.springframework.web.client.RestTemplate; public class RestTemplateUtil { private static Logger logger = LoggerFactory.getLogger(RestTemplateUtil.class); public static JSONObject postDataByRestTemplate(String url, Object params, RestTemplate restTemplate){ try { logger.info("request for:"+url); ResponseEntity entity = restTemplate.postForEntity(url, JSONObject.toJSON(params), String.class); String body = entity.getBody(); if (!body.startsWith("{")) { logger.info("response body is not start with '{' ***********************************************"); body = "{\"data\":"+body+"}"; // Feature feature = Feature.IgnoreNotMatch; return JSONObject.parseObject(body,Feature.IgnoreNotMatch); } else { return JSONObject.parseObject(body,Feature.IgnoreNotMatch); } } catch (final HttpClientErrorException httpClientErrorException) { logger.info("-------------------------------------------------------------------------------3\r\n"+url); httpClientErrorException.printStackTrace(); } catch (HttpServerErrorException httpServerErrorException) { logger.info("-------------------------------------------------------------------------------2\r\n"+url); httpServerErrorException.printStackTrace(); } catch (Exception exception) { logger.info("-------------------------------------------------------------------------------1"); exception.printStackTrace(); } return null; } public static JSONObject getDataByRestTemplate(String url, RestTemplate restTemplate){ try { logger.info("request for:"+url); ResponseEntity entity = restTemplate.getForEntity(url, String.class); String body = entity.getBody(); if (!body.startsWith("{")) { logger.info("response body is not start with '{' ***********************************************"); body = "{\"data\":"+body+"}"; return JSONObject.parseObject(body); } else { return JSONObject.parseObject(body); } } catch (final HttpClientErrorException httpClientErrorException) { logger.info("-------------------------------------------------------------------------------3\r\n"+url); httpClientErrorException.printStackTrace(); } catch (HttpServerErrorException httpServerErrorException) { logger.info("-------------------------------------------------------------------------------2\r\n"+url); httpServerErrorException.printStackTrace(); } catch (Exception exception) { logger.info("-------------------------------------------------------------------------------1"); exception.printStackTrace(); } return null; } }