import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.http.client.SimpleClientHttpRequestFactory; import org.springframework.web.client.RestTemplate; import java.io.UnsupportedEncodingException; public class RestTemplateUtil { private static Logger logger = LogManager.getLogger(RestTemplateUtil.class); public String post(String reqParam, String url) { // 核心返回結果報文字符串 String returnJson = ""; try { //復雜構造函數的使用 SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory(); requestFactory.setConnectTimeout(1000);// 設置超時 requestFactory.setReadTimeout(1000); //利用復雜構造器可以實現超時設置,內部實際實現為 HttpClient RestTemplate restTemplate = new RestTemplate(requestFactory); //設置HTTP請求頭信息,實現編碼等 HttpHeaders headers = new HttpHeaders(); MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8"); headers.setContentType(type); headers.add("Accept", MediaType.APPLICATION_JSON.toString()); //利用容器實現數據封裝,發送 HttpEntity<String> entity = new HttpEntity<String>(reqParam, headers); returnJson = restTemplate.postForObject(url, entity, String.class); // 轉碼原因:RestTemplate默認是使用org.springframework.http.converter.StringHttpMessageConverter來解析 // StringHttpMessageConverter 默認用的 ISO-8859-1來編碼的 returnJson = new String(returnJson.getBytes("ISO-8859-1"), "utf-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); logger.info("----------------------------------------"); logger.info(returnJson); logger.info("----------------------------------------"); }return returnJson; } }
