springboot之RestTemplate接口封装的示例分享

时间:2022-11-25 08:01:34

转自:

springboot之RestTemplate接口封装的示例分享

下文笔者讲述封装RestTemplate接口的示例分享,如下所示

实现思路:
    只需对RestTemplate方法进行相应的封装
	即可实现HttpClient的效果

例:

import java.util.Map;

import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;

public class RestTemplateToInterface {

	/**
	 * 
	 * @param hashMap 请求参数
	 * @param token token验证
	 * @param getOrPost get或者post请求
	 * @param url 请求路径
	 * @return
	 */
	public static Map<String, Object> getData(Map<String, Object> hashMap,String token,String getOrPost,String url) {
		RestTemplate restTemplate = new RestTemplate();
		//设置请求头,或其他需要需要的
		HttpHeaders httpHeaders = new HttpHeaders();
		httpHeaders.add("Content-Type", "application/json; charset=UTF-8");
        //设置参数;
        HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<Map<String, Object>>(hashMap, httpHeaders);
        ResponseEntity<String> resp = null;
        //执行请求
        if(getOrPost.equals("get")) {
        	resp = restTemplate.exchange(url, HttpMethod.GET, requestEntity, String.class);
        } else {
        	resp = restTemplate.exchange(url, HttpMethod.POST, requestEntity, String.class);
		}
        //获取返回数据
        String body = resp.getBody();
        Map<String, Object> res = JSON.parseObject(body, new TypeReference< Map<String,Object>>() {
        });
		return res;
	}
	
}