在项目开发中需要用到第三方接口的数据,根据我以前知道的,可以通过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;
}
}