RestTemplateUtil.java 2.46 KB
Newer Older
yuquan.zhu committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
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);

48
		@SuppressWarnings("unused")
yuquan.zhu committed
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
		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());
64
		@SuppressWarnings("unused")
yuquan.zhu committed
65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
		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();
	}

}