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

转自:

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;
	}
	
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值