springboot-RestTemplate请求第三方接口

在项目开发中需要用到第三方接口的数据,根据我以前知道的,可以通过apache common封装好的HttpClient来完成,后来我老大告诉我springboot有自带的可以去完成,我就去研究了下,后面直接写了工具类来完成第三方接口数据接收,下面直接贴代码:

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;
	}
	
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值