HTTP工具类通用之GET和POST

开箱即用

目前只写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;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
下面是一个通用Java Https请求工具类: ``` import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.ConnectException; import java.net.URL; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; public class HttpsUtil { private static class TrustAnyTrustManager implements X509TrustManager { public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { } public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { } public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[]{}; } } public static String get(String url) throws Exception { URL u = new URL(url); HttpsURLConnection conn = (HttpsURLConnection) u.openConnection(); SSLContext sslContext = SSLContext.getInstance("SSL"); sslContext.init(null, new TrustManager[]{new TrustAnyTrustManager()}, new java.security.SecureRandom()); SSLSocketFactory ssf = sslContext.getSocketFactory(); conn.setSSLSocketFactory(ssf); conn.setDoOutput(true); conn.setDoInput(true); conn.setRequestMethod("GET"); conn.connect(); InputStream is = conn.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8")); StringBuilder sb = new StringBuilder(); String line; while ((line = br.readLine()) != null) { sb.append(line); } br.close(); is.close(); conn.disconnect(); return sb.toString(); } public static String post(String url, String param) throws Exception { URL u = new URL(url); HttpsURLConnection conn = (HttpsURLConnection) u.openConnection(); SSLContext sslContext = SSLContext.getInstance("SSL"); sslContext.init(null, new TrustManager[]{new TrustAnyTrustManager()}, new java.security.SecureRandom()); SSLSocketFactory ssf = sslContext.getSocketFactory(); conn.setSSLSocketFactory(ssf); conn.setDoOutput(true); conn.setDoInput(true); conn.setRequestMethod("POST"); conn.connect(); conn.getOutputStream().write(param.getBytes("UTF-8")); InputStream is = conn.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8")); StringBuilder sb = new StringBuilder(); String line; while ((line = br.readLine()) != null) { sb.append(line); } br.close(); is.close(); conn.disconnect(); return sb.toString(); } } ``` 这个工具类可以进行Https的GET和POST请求,并且支持自签名证书。使用方法如下: ``` String url = "https://example.com/api"; String result = HttpsUtil.get(url); ``` ``` String url = "https://example.com/api"; String param = "name=value"; String result = HttpsUtil.post(url, param); ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值