平常开发中难免会调用一些外部接口,以前用的工具类也好用,但是代码比较多,如果使用的是springboot开发,可以使用restTemplate这个类,使用起来非常简单。
package com.sztf.sjgyx.util;
import com.alibaba.fastjson.JSONObject;
import com.sztf.sjgyx.common.MyException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;
import java.util.Map;
/**
* 发送接口请求工具类
*
* @author ljp
* @date 2020/10/20 15:38
*/
@Slf4j
public class HttpRequestUtil {
/**
* 发送put请求 携带参数
*
* @param url
* @param param
* @return
*/
public static String doPut(String url, Map<String, Object> param) {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity entity = new HttpEntity(param, headers);
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<String> exchange = restTemplate.exchange(url, HttpMethod.PUT, entity, String.class);
return exchange.getBody();
}
/**
* 发起get请求 携带请求头
*
* @param url
* @param token
* @return
*/
public static String doGetWithHeader(String url, String token) {
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.add("Authorization", token);
ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, new HttpEntity<String>(headers), String.class);
return response.getBody();
}
/**
* 发送无参数get请求
*
* @param url 请求路径
* @return
*/
public static String doGet(String url) {
RestTemplate restTemplate = new RestTemplate();
return restTemplate.getForObject(url, String.class);
}
/**
* 发送带参get请求
*
* @param url 请求路径
* @param param 参数
* @return
*/
public static String doGet(String url, Map<String, Object> param) {
//如果参数为空
if (null == param || param.isEmpty()) {
throw new MyException("请传递请求参数");
}
RestTemplate restTemplate = new RestTemplate();
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
//拼接参数
param.forEach(builder::queryParam);
//调用并返回
return restTemplate.getForObject(builder.build().encode().toString(), String.class);
}
/**
* 发送带参数post请求
*
* @param url 请求地址
* @param paramJson 封装参数
* @return
*/
public static String doPostWithParam(String url, JSONObject paramJson) {
RestTemplate client = new RestTemplate();
return client.postForEntity(url, paramJson, String.class).getBody();
}
}