基于java net包实现HTTPS http 的httputils

   目前大多数项目中为了实现http 、https调用 大家会引入大量的第三方jar包,但对里面的参数设置又模棱两可,导致有的项目上线后,时间一长就会出现资源耗尽的情况。但大部分人却对jdk的net包进行忽视。

package com.vivo.es;


import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.MapperFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import org.apache.commons.io.IOUtils;

import javax.net.ssl.*;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class JavaOriginalHttpClientUtil {

    public static final ObjectMapper objectMapper = new ObjectMapper();
    public static final String END = "\r\n";
    public static final String TWOHYPHENS = "--";
    public static final String BOUNDARY = "******";
    private static int CONNECT_TIMEOUT = 5000;
    private static int READ_TIMEOUT = 5000;
    private static int CHUNK_LENGTH = 128 * 1024;
    static {
        objectMapper.configure(JsonParser.Feature.ALLOW_COMMENTS, true);
        objectMapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
        objectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
        objectMapper.configure(JsonParser.Feature.ALLOW_YAML_COMMENTS, true);
        objectMapper.configure(JsonParser.Feature.AUTO_CLOSE_SOURCE, true);
        objectMapper.configure(JsonParser.Feature.IGNORE_UNDEFINED, true);
        objectMapper.configure(JsonParser.Feature.INCLUDE_SOURCE_IN_LOCATION, true);
        objectMapper.configure(JsonParser.Feature.STRICT_DUPLICATE_DETECTION, false);
        objectMapper.configure(JsonGenerator.Feature.STRICT_DUPLICATE_DETECTION, false);
        objectMapper.configure(JsonGenerator.Feature.IGNORE_UNKNOWN, true);
        objectMapper.configure(JsonGenerator.Feature.AUTO_CLOSE_JSON_CONTENT, true);
        objectMapper.configure(JsonGenerator.Feature.AUTO_CLOSE_TARGET, true);
        objectMapper.configure(JsonGenerator.Feature.WRITE_BIGDECIMAL_AS_PLAIN, false);
        objectMapper.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_ENUMS, false);
        objectMapper.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, false);
        objectMapper.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_ENUMS, false);
        objectMapper.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_VALUES, false);
        objectMapper.configure(MapperFeature.USE_WRAPPER_NAME_AS_PROPERTY_NAME, false);
        objectMapper.configure(MapperFeature.USE_STD_BEAN_NAMING, false);
        objectMapper.configure(MapperFeature.ALLOW_EXPLICIT_PROPERTY_RENAMING, false);
        objectMapper.configure(MapperFeature.ALLOW_COERCION_OF_SCALARS, true);
        objectMapper.configure(MapperFeature.IGNORE_DUPLICATE_MODULE_REGISTRATIONS, true);
        objectMapper.configure(MapperFeature.IGNORE_MERGE_FOR_UNMERGEABLE, true);
        objectMapper.configure(MapperFeature.BLOCK_UNSAFE_POLYMORPHIC_BASE_TYPES, false);
        objectMapper.configure(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS, false);
        objectMapper.configure(DeserializationFeature.USE_BIG_INTEGER_FOR_INTS, false);
        objectMapper.configure(DeserializationFeature.USE_LONG_FOR_INTS, false);
        objectMapper.configure(DeserializationFeature.USE_JAVA_ARRAY_FOR_JSON_ARRAY, false);
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, true);
        objectMapper.configure(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES, false);
        objectMapper.configure(DeserializationFeature.FAIL_ON_INVALID_SUBTYPE, true);
        objectMapper.configure(DeserializationFeature.FAIL_ON_MISSING_CREATOR_PROPERTIES, false);
        objectMapper.configure(DeserializationFeature.FAIL_ON_NULL_CREATOR_PROPERTIES, false);
        objectMapper.configure(DeserializationFeature.FAIL_ON_MISSING_EXTERNAL_TYPE_ID_PROPERTY, true);
        objectMapper.configure(DeserializationFeature.FAIL_ON_TRAILING_TOKENS, false);
        objectMapper.configure(DeserializationFeature.WRAP_EXCEPTIONS, true);
        objectMapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, false);
        objectMapper.configure(DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS, false);
        objectMapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, false);
        objectMapper.configure(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, false);
        objectMapper.configure(DeserializationFeature.READ_ENUMS_USING_TO_STRING, false);
        objectMapper.configure(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_AS_NULL, false);
        objectMapper.configure(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_USING_DEFAULT_VALUE, false);
        objectMapper.configure(DeserializationFeature.READ_DATE_TIMESTAMPS_AS_NANOSECONDS, true);
        objectMapper.configure(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE, true);
        objectMapper.configure(DeserializationFeature.EAGER_DESERIALIZER_FETCH, true);
        objectMapper.configure(SerializationFeature.WRAP_ROOT_VALUE, false);
        objectMapper.configure(SerializationFeature.INDENT_OUTPUT, false);
        objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, true);
        objectMapper.configure(SerializationFeature.FAIL_ON_SELF_REFERENCES, true);
        objectMapper.configure(SerializationFeature.WRAP_EXCEPTIONS, true);
        objectMapper.configure(SerializationFeature.FAIL_ON_UNWRAPPED_TYPE_IDENTIFIERS, true);
        objectMapper.configure(SerializationFeature.WRITE_SELF_REFERENCES_AS_NULL, false);
        objectMapper.configure(SerializationFeature.CLOSE_CLOSEABLE, false);
        objectMapper.configure(SerializationFeature.FLUSH_AFTER_WRITE_VALUE, true);
        objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, true);
        objectMapper.configure(SerializationFeature.WRITE_DATE_KEYS_AS_TIMESTAMPS, false);
        objectMapper.configure(SerializationFeature.WRITE_DATES_WITH_ZONE_ID, false);
        objectMapper.configure(SerializationFeature.WRITE_DURATIONS_AS_TIMESTAMPS, true);
        objectMapper.configure(SerializationFeature.WRITE_CHAR_ARRAYS_AS_JSON_ARRAYS, false);
        objectMapper.configure(SerializationFeature.WRITE_ENUMS_USING_TO_STRING, false);
        objectMapper.configure(SerializationFeature.WRITE_ENUMS_USING_INDEX, false);
        objectMapper.configure(SerializationFeature.WRITE_ENUM_KEYS_USING_INDEX, false);
        objectMapper.configure(SerializationFeature.WRITE_SINGLE_ELEM_ARRAYS_UNWRAPPED, false);
        objectMapper.configure(SerializationFeature.WRITE_DATE_TIMESTAMPS_AS_NANOSECONDS, true);
        objectMapper.configure(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS, false);
        objectMapper.configure(SerializationFeature.EAGER_SERIALIZER_FETCH, true);
        objectMapper.configure(SerializationFeature.USE_EQUALITY_FOR_OBJECT_ID, false);
    }

    public static void main(String[] args) throws Exception {

//        Data o = doGet("http://cis-test.vivo.xyz/cis-admin/health", null, Data.class);
//        System.out.println(o);
        HashMap<String, String> headers = new HashMap<>();
        headers.put("token", "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhY2NvdW50SWQiOiIxZmRlNjgwMmQ1YjM0NzU4ODcyYjg1YzExODhlMjUxNSIsInRlbmFudElkIjoiMmY4YWE1Y2I3NDQ3NDcwOGE2Yjg5NWRlMjVmNjRjNDkiLCJjaGFubmVsIjpudWxsLCJpc3MiOiJvM3VrVlpMa2tyQWM1SVgyazk4NEUwZG96U2ZEWlFzcSIsInBhcmFtcyI6eyJuaWNrbmFtZSI6IuadjuW6miIsImFkbWluIjpmYWxzZSwidXNlcklkIjoyOTA4fSwiZXhwIjoxNjQ4NDQ1MzY3LCJpYXQiOjE2NDg0MzgxNjd9.YLhM2lNnesyKMdCTxLoQUuisKeTlWfoB5ButOrq17yQ");
        String o1 = doGet("https://devops.vivo.xyz", headers, String.class);
        System.out.println(o1);
//        HashMap<String, String> param = new HashMap<>();
//        param.put("lg", "lg");
//        HashMap<String, List<File>> files = new HashMap<>();
        ArrayList<File> objects = new ArrayList<>();
        objects.add(new File("E:\\workspace\\spring-es\\src\\main\\java\\com\\vivo\\es\\SpringEsApplication.java"));
        objects.add(new File("E:\\workspace\\spring-es\\src\\main\\java\\com\\vivo\\es\\SpringEsApplication.java"));
        objects.add(new File("E:\\workspace\\spring-es\\src\\main\\java\\com\\vivo\\es\\SpringEsApplication.java"));
        files.put("files", objects);

        String s = doPostUploadFile("http://127.0.0.1:9998/web/uploadsinglefile", headers, param, files, String.class);
        System.out.println(s);
//
//
//        String s = doPostForm("http://127.0.0.1:9998/web/add", headers, param, String.class);
//        System.out.println(s);


    }


    public static <T> T doGet(String urlStr, Map<String, String> headers, Class<T> tClass) throws Exception {
        HttpURLConnection httpURLConnection = getConnection(urlStr);
        httpURLConnection.setRequestMethod("GET");
        if (headers != null) {
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                httpURLConnection.setRequestProperty(entry.getKey(), entry.getValue());
            }
        }
        httpURLConnection.connect();
        return getResponse(tClass, httpURLConnection);
    }


    public static <T> T doPostJson(String urlStr, Map<String, String> headers, Object param, Class<T> tClass) throws Exception {

        HttpURLConnection httpURLConnection = getConnection(urlStr);
        // 设置连接请求方式
        httpURLConnection.setRequestMethod("POST");
        // 默认值为:false,当向远程服务器传送数据/写数据时,需要设置为true
        httpURLConnection.setDoOutput(true);
        // 默认值为:true,当前向远程服务读取数据时,设置为true,该参数可有可无
        httpURLConnection.setDoInput(true);
        httpURLConnection.setRequestProperty("Content-Type", "application/json");
        if (headers != null) {
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                httpURLConnection.setRequestProperty(entry.getKey(), entry.getValue());
            }
        }
        httpURLConnection.connect();
        try (OutputStream os = httpURLConnection.getOutputStream();) {
            os.write(param instanceof String ? ((String) param).getBytes(StandardCharsets.UTF_8) : objectMapper.writeValueAsBytes(param));
            return getResponse(tClass, httpURLConnection);
        }
    }

    public static <T> T doPostForm(String urlStr, Map<String, String> headers, Map<String, String> param, Class<T> tClass) throws Exception {
        HttpURLConnection httpURLConnection = getConnection(urlStr);
        // 设置连接请求方式
        httpURLConnection.setRequestMethod("POST");
        // 默认值为:false,当向远程服务器传送数据/写数据时,需要设置为true
        httpURLConnection.setDoOutput(true);
        // 默认值为:true,当前向远程服务读取数据时,设置为true,该参数可有可无
        httpURLConnection.setDoInput(true);
        // 设置传入参数的格式:请求参数应该是 name1=value1&name2=value2 的形式。
        httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        if (headers != null) {
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                httpURLConnection.setRequestProperty(entry.getKey(), entry.getValue());
            }
        }
        httpURLConnection.connect();
        try (OutputStream os = httpURLConnection.getOutputStream();) {
            os.write(createLinkString(param).getBytes(StandardCharsets.UTF_8));
            return getResponse(tClass, httpURLConnection);
        }

    }



    public static <T> T doPostUploadFile(String urlStr, Map<String, String> headers, Map<String, String> param, Map<String, List<File>> uploadFiles, Class<T> tClass) throws Exception {
        OutputStream outputStream = null;
        try {

            HttpURLConnection urlConnection = getConnection(urlStr);
            urlConnection.setChunkedStreamingMode(CHUNK_LENGTH);
            urlConnection.setDoInput(true);
            urlConnection.setDoOutput(true);
            urlConnection.setUseCaches(true);
            urlConnection.setRequestMethod("POST");
            urlConnection.setRequestProperty("Connection", "close");
            urlConnection.setRequestProperty("Charset", "UTF-8");
            urlConnection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + BOUNDARY);
            if (headers != null) {
                for (Map.Entry<String, String> entry : headers.entrySet()) {
                    urlConnection.setRequestProperty(entry.getKey(), entry.getValue());
                }
            }
            outputStream = urlConnection.getOutputStream();
            // 处理文本==============================
            if (param != null) {
                for (Map.Entry<String, String> entry : param.entrySet()) {
                    String name = entry.getKey();
                    String value = entry.getValue();
                    if (value == null) {
                        continue;
                    }
                    value = new String(value.getBytes("utf-8"));
                    String strData = END + TWOHYPHENS + BOUNDARY + END;
                    outputStream.write(strData.getBytes(StandardCharsets.UTF_8));
                    strData = "Content-Disposition: form-data; name=\"" + name + "\"" + END + END + value;
                    outputStream.write(strData.getBytes(StandardCharsets.UTF_8));
                }
            }
// 处理文件上传==============================
            if (uploadFiles != null) {
                for (Map.Entry<String, List<File>> entry : uploadFiles.entrySet()) {
                    String name = entry.getKey();
                    List<File> files = entry.getValue();
                    if (files == null || files.isEmpty()) {
                        continue;
                    }
                    for (File file : files) {
                        outputStream.write((END + TWOHYPHENS + BOUNDARY + END).getBytes(StandardCharsets.UTF_8));
                        outputStream.write(("Content-Disposition: form-data; name=\"" + name + "\"; filename=\""
                                + file.getName() + "\"" + END).getBytes(StandardCharsets.UTF_8));
                        outputStream.write(END.getBytes(StandardCharsets.UTF_8));
                        try (InputStream inputStream = new FileInputStream(file)) {
                            IOUtils.copy(inputStream,outputStream,1024*1024);
                        }
                    }

                }
            }
            outputStream.write(END.getBytes(StandardCharsets.UTF_8));
            outputStream.write((TWOHYPHENS + BOUNDARY + TWOHYPHENS + END).getBytes(StandardCharsets.UTF_8));
            outputStream.flush();
            return getResponse(tClass, urlConnection);
        } finally {
            IOUtils.close(outputStream);
        }
    }

    private static <T> T getResponse(Class<T> tClass, HttpURLConnection urlConnection) throws IOException {
        try (InputStream inputStream = urlConnection.getInputStream();
             ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()) {
            IOUtils.copy(inputStream, byteArrayOutputStream);
            String message = new String(byteArrayOutputStream.toByteArray());
            if (urlConnection.getResponseCode() == 200) {
                if (tClass.isAssignableFrom(String.class)) {
                    return (T) message;
                }
                return objectMapper.readValue(message, tClass);
            } else {
                throw new HttpException(urlConnection.getResponseCode(), message);
            }
        }
    }


    /**
     * 把数组所有元素排序,并按照“参数=参数值”的模式用“&”字符拼接成字符串
     *
     * @param params 需要排序并参与字符拼接的参数组
     * @return 拼接后字符串
     */
    public static String createLinkString(Map<String, String> params) {
        StringBuilder prestr = new StringBuilder();
        if (params != null && !params.isEmpty()) {
            int i = 0;
            for (Map.Entry<String, String> entry : params.entrySet()) {
                String key = entry.getKey();
                String value = entry.getValue();
                if (i == params.size() - 1) {// 拼接时,不包括最后一个&字符
                    prestr.append(key).append("=").append(value);
                } else {
                    prestr.append(key).append("=").append(value).append("&");
                }
            }
        }
        return prestr.toString();
    }

    private static HttpURLConnection getConnection(String urlStr) throws Exception {
        URL url = new URL(urlStr);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        if (connection instanceof HttpsURLConnection) {
            HttpsURLConnection sCon = (HttpsURLConnection) connection;
            SSLContext instance = SSLContext.getInstance("TLSv1.2");
            instance.init(null,new TrustManager[]{
                    new X509TrustManager() {
                        @Override
                        public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {

                        }

                        @Override
                        public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {

                        }

                        @Override
                        public X509Certificate[] getAcceptedIssuers() {
                            return null;
                        }
                    }
            },new SecureRandom());
            sCon.setSSLSocketFactory(instance.getSocketFactory());
            sCon.setHostnameVerifier(new HostnameVerifier() {

                @Override
                public boolean verify(String arg0, SSLSession arg1) {
                    // TODO Auto-generated method stub
                    return true;
                }
            });

        }
        connection.setUseCaches(true);
        connection.setInstanceFollowRedirects(true);
        connection.setConnectTimeout(CONNECT_TIMEOUT);
        connection.setReadTimeout(READ_TIMEOUT);
        return connection;
    }


}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值