• java有关的HttpsUtils工具类 https请求工具类


    package com.nugget.utils;
    
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.net.HttpURLConnection;
    import java.net.URL;
    import java.net.URLEncoder;
    import java.nio.charset.Charset;
    import java.security.SecureRandom;
    import java.security.cert.CertificateException;
    import java.security.cert.X509Certificate;
    import java.util.Arrays;
    import java.util.HashMap;
    import java.util.Map;
    
    import javax.net.ssl.HostnameVerifier;
    import javax.net.ssl.HttpsURLConnection;
    import javax.net.ssl.SSLContext;
    import javax.net.ssl.SSLSession;
    import javax.net.ssl.TrustManager;
    import javax.net.ssl.X509TrustManager;
    
    import com.alibaba.fastjson.JSONObject;
    import com.alibaba.fastjson.serializer.SerializerFeature;
    
    public class HttpsUtils {
        public static String METHOD_GET = "GET";
        public static String METHOD_POST = "POST";
    
        public static int DEF_CONNECT_TIMEOUT = 2 * 1000;
        public static int DEF_READ_TIMEOUT = 8 * 1000;
        public static Charset DEF_CHARSET = Charset.forName("UTF-8");
        public static void main(String[] args) {
            JSONObject x=HttpsUtils.doGetAuthorization("https://amzrealtime.despatchcloud.co.uk/ws/v1/wsfulfilment/list_fulfilment_clients");
            System.out.println(x);
        }
        public static JSONObject doGetAuthorization(String url) {
            Map<String, String> headers=new HashMap<>();
            headers.put("Authorization", "DC 454");
            String xx=HttpsUtils.Get(url, headers);
            return JSONObject.parseObject(xx);
        }
        public static TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return new java.security.cert.X509Certificate[]{};
            }
            @Override
            public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            }
            @Override
            public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            }
        }};
        public static void trustAll() {
            try {
                SSLContext sc = SSLContext.getInstance("TLS");
                sc.init(null, trustAllCerts, new java.security.SecureRandom());
                HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        static {
            trustAll();
        }
    
        public static String Get(String urlString) {
            return HttpsGo(urlString, METHOD_GET, null, null, DEF_CONNECT_TIMEOUT, DEF_READ_TIMEOUT);
        }
    
        public static String Get(String urlString, Map<String, String> headers) {
            return HttpsGo(urlString, METHOD_GET, headers, null, DEF_CONNECT_TIMEOUT, DEF_READ_TIMEOUT);
        }
    
        public static String Get(String urlString, Map<String, String> headers, Map<String, String> params) {
            if (params != null && params.isEmpty() == false) {
                StringBuffer url = new StringBuffer(urlString);
                try {
                    boolean isFirst = true;
                    if (urlString.contains("?")) {
                        if (urlString.endsWith("&") == false && urlString.contains("&")) {
                            isFirst = false;
                        }
                    } else {
                        url.append('?');
                    }
                    String paramsEncoding = DEF_CHARSET.name();
                    for (Map.Entry<String, String> entry : params.entrySet()) {
                        if (isFirst) isFirst = false; else url.append('&');
                        url.append(URLEncoder.encode(entry.getKey(), paramsEncoding));
                        url.append('=');
                        url.append(URLEncoder.encode(entry.getValue(), paramsEncoding));
                    }
                } catch (Exception e) {
                }
                return Get(url.toString(), headers);
            } else {
                return Get(urlString, headers);
            }
        }
    
        public static String Post(String urlString, String contentType, byte[] content) {
            Map<String, String> headers = new HashMap<String, String>(1);
            headers.put("Content-Type", contentType);
            return HttpsGo(urlString, METHOD_POST, headers, content, DEF_CONNECT_TIMEOUT, DEF_READ_TIMEOUT);
        }
    
        public static String FormPost(String urlString, String content) {
            Map<String, String> headers = new HashMap<String, String>(1);
            headers.put("Content-Type", String.format("application/x-www-form-urlencoded; charset=%s", DEF_CHARSET.name()));
            return HttpsGo(urlString, METHOD_POST, null, content.getBytes(DEF_CHARSET), DEF_CONNECT_TIMEOUT, DEF_READ_TIMEOUT);
        }
    
        public static String XmlPost(String urlString, String content) {
            Map<String, String> headers = new HashMap<String, String>(1);
            headers.put("Content-Type", String.format("text/html; charset=%s", DEF_CHARSET.name()));
            return HttpsGo(urlString, METHOD_POST, headers, content.getBytes(DEF_CHARSET), DEF_CONNECT_TIMEOUT, DEF_READ_TIMEOUT);
        }
    
        public static String JsonPost(String urlString, Object content) {
            return JsonPost(urlString, JSONObject.toJSONString(content, SerializerFeature.DisableCircularReferenceDetect));
        }
    
        public static String JsonPost(String urlString, String content) {
            Map<String, String> headers = new HashMap<String, String>(1);
            headers.put("Content-Type", String.format("application/json; charset=%s", DEF_CHARSET.name()));
            return HttpsGo(urlString, METHOD_POST, headers, content.getBytes(DEF_CHARSET), DEF_CONNECT_TIMEOUT, DEF_READ_TIMEOUT);
        }
    
        public static String HttpsGo(String urlString, String method, Map<String, String> headers, byte[] content, int connectTimeout, int readTimeout) {
            HttpsURLConnection conn = null;
            try {
                conn = (HttpsURLConnection) new URL(urlString).openConnection();
    
                SSLContext sc = SSLContext.getInstance("SSL");
                sc.init(null, trustAllCerts, new SecureRandom());
                conn.setHostnameVerifier(new HostnameVerifier() {
                    @Override
                    public boolean verify(String arg0, SSLSession arg1) {
                        return true;
                    }
                });
                conn.setSSLSocketFactory(sc.getSocketFactory());
    
                conn.setRequestMethod(method);
                conn.setDoOutput(true);
                conn.setDoInput(true);
                conn.setUseCaches(false);
                conn.setConnectTimeout(connectTimeout);
                conn.setReadTimeout(readTimeout);
    
                if (headers != null) {
                    for (Map.Entry<String, String> entry : headers.entrySet()) {
                        conn.addRequestProperty(entry.getKey(), entry.getValue());
                    }
                }
                if (content != null) {
                    if (headers == null || headers.containsKey("Content-Length") == false) {
                        conn.addRequestProperty("Content-Length", Integer.toString(content.length));
                    }
                    OutputStream output = null;
                    try {
                        output = conn.getOutputStream();
                        output.write(content);
                        output.flush();
                    } finally {
                        if (output != null) try { output.close(); } catch (Exception e) { }
                    }
                }
    
                return readContent(conn.getResponseCode() == 200 ? conn.getInputStream() : conn.getErrorStream(), getCharset(conn));
            } catch (Exception e) {
                return null;
            } finally {
                if (conn != null) conn.disconnect();
            }
        }
    
        public static String encodeParams(Map<String, String> params, String paramsEncoding) throws Exception {
            boolean isFirst = true;
            StringBuilder encodedParams = new StringBuilder();
            for (Map.Entry<String, String> entry : params.entrySet()) {
                if (isFirst) isFirst = false; else encodedParams.append('&');
                encodedParams.append(URLEncoder.encode(entry.getKey(), paramsEncoding));
                encodedParams.append('=');
                encodedParams.append(URLEncoder.encode(entry.getValue(), paramsEncoding));
            }
            return encodedParams.toString();
        }
    
        public static String CHARSET_DEF = DEF_CHARSET.name();
        private static String CHARSET_STR = "charset=";
        private static int CHARSET_STR_LEN = CHARSET_STR.length();
        private static String getCharset(HttpURLConnection conn) {
            String contentType = conn.getHeaderField("Content-Type");
            int length = contentType != null ? contentType.length() : 0;
            if (length < CHARSET_STR_LEN) {
                return CHARSET_DEF;
            }
            int pos = contentType != null ? contentType.indexOf("charset=") : -1;
            if (pos < 0) {
                return CHARSET_DEF;
            }
            return contentType.substring(pos + CHARSET_STR_LEN);
        }
    
        private static String readContent(InputStream input, String charset) throws Exception {
            try {
                int APPEND_LEN = 4 * 1024;
                int offset = 0;
                byte[] data = new byte[APPEND_LEN];
                while (true) {
                    int len = input.read(data, offset, data.length - offset);
                    if (len == -1) {
                        break;
                    }
                    offset += len;
                    if (offset >= data.length) {
                        data = Arrays.copyOf(data, offset + APPEND_LEN);
                    }
                }
                return charset != null ? new String(data, 0, offset, charset) : new String(data, 0, offset);
            } finally {
                if (input != null) try { input.close(); } catch (Exception e) { }
            }
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
    • 140
    • 141
    • 142
    • 143
    • 144
    • 145
    • 146
    • 147
    • 148
    • 149
    • 150
    • 151
    • 152
    • 153
    • 154
    • 155
    • 156
    • 157
    • 158
    • 159
    • 160
    • 161
    • 162
    • 163
    • 164
    • 165
    • 166
    • 167
    • 168
    • 169
    • 170
    • 171
    • 172
    • 173
    • 174
    • 175
    • 176
    • 177
    • 178
    • 179
    • 180
    • 181
    • 182
    • 183
    • 184
    • 185
    • 186
    • 187
    • 188
    • 189
    • 190
    • 191
    • 192
    • 193
    • 194
    • 195
    • 196
    • 197
    • 198
    • 199
    • 200
    • 201
    • 202
    • 203
    • 204
    • 205
    • 206
    • 207
    • 208
    • 209
    • 210
    • 211
    • 212
    • 213
    • 214
    • 215
    • 216
    • 217
    • 218
    • 219
    • 220
    • 221
    • 222
    • 223
    • 224
    • 225
    • 226
    • 227
    • 228
  • 相关阅读:
    专业扫盲, 熬夜整理56个JavaScript高级的手写知识点【史上最全】
    算法分析与设计——要求根据给定的正整数n计算第n个斐波那契数。
    【代码随想录】算法训练营 第十八天 第六章 二叉树 Part 5
    捷报|数说故事同期斩获虎啸奖、弯弓奖六项大奖
    Android 接入腾讯IM即时通信(详细图文)
    论文分享|NeurIPS2022‘华盛顿大学|俄罗斯套娃表示学习(OpenAI使用的文本表示学习技术)
    element ui文件上传方法中需要传额外参数
    Multi Modal Smart Diagnosis of Pulmonary Diseases
    处理.git文件夹过大出现臃肿问题-filter-branch和BFG工具
    Java多并发(二)| cas & synchronized & volatile的内存语义
  • 原文地址:https://blog.csdn.net/billionyearsbo/article/details/128214998