chengkun
2025-06-05 4080b5997b38ca84b3b203c7101dcadb97b76925
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
package com.alipay.easysdk.kms.aliyun.credentials.http;
 
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.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import java.util.Map;
 
public class CompatibleUrlConnClient implements Closeable {
    protected static final String ACCEPT_ENCODING = "Accept-Encoding";
 
    public static HttpResponse compatibleGetResponse(HttpRequest request)
            throws IOException, NoSuchAlgorithmException, KeyManagementException {
        CompatibleUrlConnClient client = new CompatibleUrlConnClient();
        HttpResponse response = client.syncInvoke(request);
        client.close();
        return response;
    }
 
    public HttpResponse syncInvoke(HttpRequest request) throws IOException, NoSuchAlgorithmException, KeyManagementException {
        InputStream content = null;
        HttpResponse response = null;
        HttpURLConnection httpConn = buildHttpConnection(request);
 
        try {
            httpConn.connect();
            content = httpConn.getInputStream();
            response = new HttpResponse(httpConn.getURL().toString());
            parseHttpConn(response, httpConn, content);
            return response;
        } catch (IOException e) {
            content = httpConn.getErrorStream();
            response = new HttpResponse(httpConn.getURL().toString());
            parseHttpConn(response, httpConn, content);
            return response;
        } finally {
            if (content != null) {
                content.close();
            }
            httpConn.disconnect();
        }
    }
 
    public SSLSocketFactory createSSLSocketFactory() throws NoSuchAlgorithmException, KeyManagementException {
        X509TrustManager compositeX509TrustManager = new CompositeX509TrustManager();
        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, new TrustManager[] {compositeX509TrustManager}, new java.security.SecureRandom());
        return sslContext.getSocketFactory();
    }
 
    public void checkHttpRequest(HttpRequest request) {
        String strUrl = request.getUrl();
        if (null == strUrl) {
            throw new IllegalArgumentException("URL is null for HttpRequest.");
        }
        if (null == request.getMethod()) {
            throw new IllegalArgumentException("Method is not set for HttpRequest.");
        }
    }
 
    public HttpURLConnection initHttpConnection(URL url, HttpRequest request)
            throws IOException, KeyManagementException, NoSuchAlgorithmException {
        HttpURLConnection httpConn;
        if ("https".equalsIgnoreCase(url.getProtocol())) {
            HttpsURLConnection httpsConn = (HttpsURLConnection) url.openConnection();
            SSLSocketFactory sslSocketFactory = createSSLSocketFactory();
            httpsConn.setSSLSocketFactory(sslSocketFactory);
            httpsConn.setHostnameVerifier(new TrueHostnameVerifier());
            httpConn = httpsConn;
        } else {
            httpConn = (HttpURLConnection) url.openConnection();
        }
        httpConn.setRequestMethod(request.getMethod().toString());
        httpConn.setInstanceFollowRedirects(false);
        httpConn.setDoOutput(true);
        httpConn.setDoInput(true);
        httpConn.setUseCaches(false);
        httpConn.setConnectTimeout(request.getConnectTimeout());
        httpConn.setReadTimeout(request.getReadTimeout());
        httpConn.setRequestProperty(ACCEPT_ENCODING, "identity");
        return httpConn;
    }
 
    public HttpURLConnection buildHttpConnection(HttpRequest request) throws IOException, NoSuchAlgorithmException, KeyManagementException {
        checkHttpRequest(request);
        String strUrl = request.getUrl();
        URL url = new URL(strUrl);
        System.setProperty("sun.net.http.allowRestrictedHeaders", "true");
        HttpURLConnection httpConn = initHttpConnection(url, request);
        return httpConn;
    }
 
    public void parseHttpConn(HttpResponse response, HttpURLConnection httpConn, InputStream content)
            throws IOException, NoSuchAlgorithmException {
        byte[] buff = readContent(content);
        response.setStatus(httpConn.getResponseCode());
        response.setResponseMessage(httpConn.getResponseMessage());
        Map<String, List<String>> headers = httpConn.getHeaderFields();
        for (Map.Entry<String, List<String>> entry : headers.entrySet()) {
            String key = entry.getKey();
            if (null == key) {
                continue;
            }
            List<String> values = entry.getValue();
            StringBuilder builder = new StringBuilder(values.get(0));
            for (int i = 1; i < values.size(); i++) {
                builder.append(",");
                builder.append(values.get(i));
            }
            response.putHeaderParameter(key, builder.toString());
        }
        String type = response.getHeaderValue("Content-Type");
        if (buff != null && type != null) {
            response.setEncoding("UTF-8");
            String[] split = type.split(";");
            response.setHttpContentType(FormatType.mapAcceptToFormat(split[0].trim()));
            if (split.length > 1 && split[1].contains("=")) {
                String[] codings = split[1].split("=");
                response.setEncoding(codings[1].trim().toUpperCase());
            }
        }
        response.setHttpContent(buff, response.getEncoding(), response.getHttpContentType());
    }
 
    private byte[] readContent(InputStream content) throws IOException {
        if (content == null) {
            return null;
        }
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        byte[] buff = new byte[1024];
        while (true) {
            final int read = content.read(buff);
            if (read == -1) {
                break;
            }
            outputStream.write(buff, 0, read);
        }
        return outputStream.toByteArray();
    }
 
    @Override
    public void close() throws IOException {
 
    }
}