HttpUtils.java 6.6 KB
Newer Older
L
ligang 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
17

Q
qiaozhanwei 已提交
18
package org.apache.dolphinscheduler.common.utils;
L
ligang 已提交
19

Q
qiaozhanwei 已提交
20
import org.apache.dolphinscheduler.common.Constants;
21

L
ligang 已提交
22
import org.apache.http.HttpEntity;
F
felix.wang 已提交
23 24
import org.apache.http.client.config.AuthSchemes;
import org.apache.http.client.config.CookieSpecs;
L
ligang 已提交
25 26 27
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
F
felix.wang 已提交
28 29 30 31 32 33
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
L
ligang 已提交
34 35
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
F
felix.wang 已提交
36
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
L
ligang 已提交
37 38 39
import org.apache.http.util.EntityUtils;

import java.io.IOException;
F
felix.wang 已提交
40 41 42 43
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import java.util.Arrays;
44 45 46 47 48 49 50 51

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

L
ligang 已提交
52 53 54 55
/**
 * http utils
 */
public class HttpUtils {
F
felix.wang 已提交
56

57
    public static final Logger logger = LoggerFactory.getLogger(HttpUtils.class);
F
felix.wang 已提交
58

59 60 61
    private HttpUtils() {
        throw new UnsupportedOperationException("Construct HttpUtils");
    }
F
felix.wang 已提交
62

63 64 65
    public static CloseableHttpClient getInstance() {
        return HttpClientInstance.httpClient;
    }
F
felix.wang 已提交
66

67 68 69
    private static class HttpClientInstance {
        private static final CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(cm).setDefaultRequestConfig(requestConfig).build();
    }
F
felix.wang 已提交
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
    private static PoolingHttpClientConnectionManager cm;

    private static SSLContext ctx = null;

    private static SSLConnectionSocketFactory socketFactory;

    private static RequestConfig requestConfig;

    private static Registry<ConnectionSocketFactory> socketFactoryRegistry;

    private static X509TrustManager xtm = new X509TrustManager() {
        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType) {
        }

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType) {
        }

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }
    };

    static {
        try {
            ctx = SSLContext.getInstance(SSLConnectionSocketFactory.TLS);
            ctx.init(null, new TrustManager[]{xtm}, null);
        } catch (NoSuchAlgorithmException e) {
            logger.error("SSLContext init with NoSuchAlgorithmException", e);
        } catch (KeyManagementException e) {
            logger.error("SSLContext init with KeyManagementException", e);
        }
        socketFactory = new SSLConnectionSocketFactory(ctx, NoopHostnameVerifier.INSTANCE);
        /** set timeout、request time、socket timeout */
        requestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.IGNORE_COOKIES)
                .setExpectContinueEnabled(Boolean.TRUE)
                .setTargetPreferredAuthSchemes(Arrays.asList(AuthSchemes.NTLM, AuthSchemes.DIGEST))
                .setProxyPreferredAuthSchemes(Arrays.asList(AuthSchemes.BASIC))
                .setConnectTimeout(Constants.HTTP_CONNECT_TIMEOUT).setSocketTimeout(Constants.SOCKET_TIMEOUT)
                .setConnectionRequestTimeout(Constants.HTTP_CONNECTION_REQUEST_TIMEOUT).setRedirectsEnabled(true)
                .build();
        socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("http", PlainConnectionSocketFactory.INSTANCE).register("https", socketFactory).build();
        cm = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
        cm.setDefaultMaxPerRoute(60);
        cm.setMaxTotal(100);
F
felix.wang 已提交
120

121
    }
122

123 124 125 126 127 128 129 130
    /**
     * get http request content
     *
     * @param url url
     * @return http get request response content
     */
    public static String get(String url) {
        CloseableHttpClient httpclient = HttpUtils.getInstance();
L
ligang 已提交
131

132 133
        HttpGet httpget = new HttpGet(url);
        return getResponseContentString(httpget, httpclient);
134 135 136 137 138
    }

    /**
     * get http response content
     *
139
     * @param httpget httpget
140 141 142 143
     * @param httpClient httpClient
     * @return http get request response content
     */
    public static String getResponseContentString(HttpGet httpget, CloseableHttpClient httpClient) {
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
        String responseContent = null;
        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(httpget);
            // check response status is 200
            if (response.getStatusLine().getStatusCode() == 200) {
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    responseContent = EntityUtils.toString(entity, Constants.UTF_8);
                } else {
                    logger.warn("http entity is null");
                }
            } else {
                logger.error("http get:{} response status code is not 200!", response.getStatusLine().getStatusCode());
            }
        } catch (IOException ioe) {
            logger.error(ioe.getMessage(), ioe);
        } finally {
            try {
                if (response != null) {
                    EntityUtils.consume(response.getEntity());
                    response.close();
                }
            } catch (IOException e) {
                logger.error(e.getMessage(), e);
            }
            if (!httpget.isAborted()) {
                httpget.releaseConnection();
                httpget.abort();
            }

        }
        return responseContent;
177
    }
L
ligang 已提交
178 179

}