您好,欢迎来到星星旅游。
搜索
您的当前位置:首页springboot-RestTemplate请求第三方接口

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;
	}
	
}

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- stra.cn 版权所有 赣ICP备2024042791号-4

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务