开箱即用
目前只写get和post请求,剩下的自行扩展
get请求发送实体,需要拼接到url上,不能直接发送,故采用发射获取实体对象数据,转换为可发送的格式进行发送,get接收直接使用对象接收,不需要加注解
如果想结果是自己需要的内容,可以外加包装一层,使用gosn或者json工具进行转换即可
import com.google.common.base.Joiner;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMethod;
import java.io.*;
import java.lang.reflect.Field;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
@Slf4j
@Component
public class HttpClientUtil {
/**
* 请求调用
*
* @param uri 地址
* @param requestMethod 请求方式:get、post
* @param body 请求体
* @param headerMap 头部信息
* @param contentType 文本类型
* @return {@link String} 结果
* @throws IOException 异常
*/
public static String invokeRequest(String uri, String requestMethod, String body, Map<String, String> headerMap, String contentType) throws IOException {
URL url = new URL(uri);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod(requestMethod);
if (Objects.nonNull(headerMap) && !headerMap.isEmpty()) {
headerMap.forEach(httpURLConnection::setRequestProperty);
}
if (StringUtils.isNotBlank(contentType)) {
httpURLConnection.setRequestProperty("Content-Type", contentType);
}
httpURLConnection.setDoInput(Boolean.TRUE);
if (StringUtils.isNotBlank(body)) {
httpURLConnection.setDoOutput(Boolean.TRUE);
}
httpURLConnection.connect();
if (StringUtils.isNotBlank(body)) {
OutputStream outputStream = httpURLConnection.getOutputStream();
outputStream.write(body.getBytes());
outputStream.flush();
outputStream.close();
}
InputStream inputStream = null;
InputStreamReader isr = null;
BufferedReader br = null;
try {
inputStream = httpURLConnection.getInputStream();
isr = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
br = new BufferedReader(isr);
StringBuilder contentSB = new StringBuilder();
String content;
while (StringUtils.isNotBlank((content = br.readLine()))) {
contentSB.append(content);
}
return contentSB.toString();
} catch (Exception e) {
log.error("请求接口异常,接口:{},请求方式:{},参数:{},请求头:{},Content-Type:{},异常信息:{}",
url.getPath(), requestMethod, body, headerMap, contentType, ExceptionUtils.getStackTrace(e));
throw new RuntimeException(e.getMessage());
} finally {
if (Objects.nonNull(br)) {
br.close();
}
if (Objects.nonNull(isr)) {
isr.close();
}
if (Objects.nonNull(inputStream)) {
inputStream.close();
}
}
}
public static String post(String url, String body) {
return post(url, body, null, null);
}
public static String post(String url, String body, Map<String, String> headerMap) {
return post(url, body, headerMap, null);
}
public static String post(String url, String body, Map<String, String> headerMap, String contentType) {
if (StringUtils.isBlank(contentType)) {
contentType = "application/json; charset=utf-8";
}
try {
return invokeRequest(url, RequestMethod.POST.name(), body, headerMap, contentType);
} catch (IOException e) {
throw new RuntimeException(e.getMessage());
}
}
public static String get(String url) {
return get(url, null, null, null);
}
public static String get(String url, Object body) {
return get(url, body, null, null);
}
public static String get(String url, Object body, Map<String, String> headerMap) {
return get(url, body, headerMap, null);
}
public static String get(String url, Object body, Map<String, String> headerMap, String contentType) {
try {
String urlParam = generateGetParam(body);
if (StringUtils.isNotBlank(urlParam)) {
url = url + "?" + urlParam;
}
return invokeRequest(url, RequestMethod.GET.name(), null, headerMap, contentType);
} catch (Exception e) {
log.error("GET请求异常,url:{},body:{},header:{},contentType:{},异常信息:{}", url, body, headerMap, contentType, ExceptionUtils.getMessage(e));
throw new RuntimeException(e.getMessage());
}
}
/**
* 生成get请求参数
*
* @param body 请求体
* @return 拼接到get请求url后面的参数
*/
private static String generateGetParam(Object body) throws IllegalAccessException, UnsupportedEncodingException {
if (Objects.isNull(body)) {
return null;
}
Field[] declaredFields = body.getClass().getDeclaredFields();
List<String> resList = listDeclaredField(declaredFields, body);
Class<?> superclass = body.getClass().getSuperclass();
if (Objects.nonNull(superclass)) {
declaredFields = superclass.getDeclaredFields();
resList.addAll(listDeclaredField(declaredFields, body));
}
if (CollectionUtils.isEmpty(resList)) {
return null;
}
//可以自行拼接
return Joiner.on("&").join(resList);
}
/**
* 获取对象属性和值
* @param declaredFields 属性字段
* @param body 对象
* @return {@link List}<{@link String}>
*/
private static List<String> listDeclaredField(Field[] declaredFields, Object body) throws IllegalAccessException, UnsupportedEncodingException {
List<String> resList = new ArrayList<>();
if (Objects.isNull(declaredFields)) {
return resList;
}
for (Field declaredField : declaredFields) {
declaredField.setAccessible(Boolean.TRUE);
Object o = declaredField.get(body);
if (Objects.isNull(o)) {
continue;
}
resList.add(declaredField.getName() + "=" + URLEncoder.encode(String.valueOf(o), StandardCharsets.UTF_8.name()));
}
return resList;
}
}