package cn.timer.api.utils; import javax.servlet.http.HttpSession; import org.apache.poi.ss.formula.functions.T; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.stereotype.Component; import org.springframework.util.MultiValueMap; import org.springframework.web.client.RestTemplate; import com.alibaba.fastjson.JSONObject; /** * @author Eangaie * @date 2018/10/12 0012 下午 14:53 网络请求,RestTemplate工具类 */ @Component public class RestTemplateUtil { @Autowired private RestTemplate restTemplate; @Autowired private HttpSession session; /** * 发送GET请求 * * @param url * @param param * @return */ public JSONObject GetData(String url, T param) { // 请勿轻易改变此提交方式,大部分的情况下,提交方式都是表单提交 HttpHeaders headers = new HttpHeaders(); headers.add("appid", "4438775940"); headers.add("grantType", "refresh_token"); headers.add("refreshToken", "8b58973c290cc848b67ff0017cd424ff"); session.setAttribute("Content-Type", "application/json"); session.setAttribute("X-Tsign-Open-App-Id", "4438775940"); session.setAttribute("X-Tsign-Open-Token", "token"); headers.setContentType(MediaType.APPLICATION_JSON_UTF8); @SuppressWarnings("unused") HttpEntity<T> httpEntity = new HttpEntity<T>(param, headers); return restTemplate.getForEntity(url, JSONObject.class, param).getBody(); } /** * 发送POST-JSON请求 * * @param url * @param param * @return */ public String PostJsonData(String url, JSONObject param) { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON_UTF8); headers.add("Accept", MediaType.APPLICATION_JSON.toString()); @SuppressWarnings("unused") HttpEntity<JSONObject> requestEntity = new HttpEntity<JSONObject>(param, headers); return restTemplate.postForEntity(url, param, String.class).getBody(); } /** * 发送POST 表单请求 * * @param url * @param param * @return */ public String PostFormData(String url, MultiValueMap<String, String> param) { // 请勿轻易改变此提交方式,大部分的情况下,提交方式都是表单提交 HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); return restTemplate.postForEntity(url, param, String.class).getBody(); } }