import java.io.*;
import java.net.*;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

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

import org.apache.commons.httpclient.HttpException;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.*;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.params.ConnRoutePNames;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.*;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

@SuppressWarnings("deprecation")
public class HttpUtil {

    //注册端口
    //private static int port = 443;
    //超时时间(毫秒)
    private final static int CONNECTION_TIME_OUT = 10000;

    public static final int READDATA_TIMEOUT = 10000;// 数据读取等待超时

    protected static Log log = LogFactory.getLog(HttpUtil.class);

    public synchronized static String sendDataByGet(String url,
                                                    Map<String, String> params, boolean enableProxy, int timeout) {

        if (params != null && params.size() > 0) {
            StringBuffer sb = new StringBuffer();
            Set<Entry<String, String>> set = params.entrySet();
            for (Iterator<Entry<String, String>> iterator = set.iterator(); iterator.hasNext(); ) {
                Entry<String, String> entry = (Entry<String, String>) iterator.next();
                sb.append("&" + entry.getKey() + "=" + URLEncoder.encode(entry.getValue()));
            }
            if (url.indexOf("?") == -1) {
                sb.deleteCharAt(0);
                url = url + "?" + sb.toString();
            } else {
                url = url + sb.toString();
            }
        }

        DefaultHttpClient client = null;

        if (client == null) {
            client = createHttpClient(timeout);
        }

        if (enableProxy) {
            HttpHost host = new HttpHost("10.37.84.16", 80);
            client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, host);
            client.getCredentialsProvider().setCredentials(new AuthScope("10.37.84.16", 80), new UsernamePasswordCredentials("um", "密码"));
        }
        HttpGet get = new HttpGet(url);
        HttpResponse resp = null;
        String result = null;
        try {
            resp = client.execute(get);
            if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK
                    || resp.getStatusLine().getStatusCode() == 400) {
                result = EntityUtils.toString(resp.getEntity(), HTTP.UTF_8);
                System.out.println(result);
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {

            e.printStackTrace();
        } catch (Exception e) {

            e.printStackTrace();
        }
        return result;
    }

    public synchronized static String sendDataByPost(String url,
                                                     List<NameValuePair> datas, boolean enableProxy, int timeout) {
        DefaultHttpClient client = null;

        if (client == null) {
            client = createHttpClient(timeout);
        }
        if (enableProxy) {
            HttpHost host = new HttpHost("10.37.84.16", 80);
            client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, host);
            client.getCredentialsProvider().setCredentials(new AuthScope("10.37.84.16", 80), new UsernamePasswordCredentials("gengqian499", "gq1234!@#$"));
        }
        HttpPost post = new HttpPost(url);

        HttpResponse resp = null;
        String result = null;
        try {
            post.setEntity(new UrlEncodedFormEntity(datas, HTTP.UTF_8));
            resp = client.execute(post);
            if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK
                    || resp.getStatusLine().getStatusCode() == 400) {
                result = EntityUtils.toString(resp.getEntity(), HTTP.UTF_8);
                System.out.println(result);
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {

            e.printStackTrace();
        } catch (Exception e) {

            e.printStackTrace();
        }
        return result;
    }
    public static String doGet(String url) throws IOException {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(url);
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(CONNECTION_TIME_OUT).setConnectTimeout(CONNECTION_TIME_OUT).build();
        httpGet.setConfig(requestConfig);
        try {
            HttpResponse resp = httpClient.execute(httpGet);
            String result = EntityUtils.toString(resp.getEntity(), HTTP.UTF_8);
            int statusCode = resp.getStatusLine().getStatusCode();
            if (statusCode == HttpStatus.SC_OK) {
                return result;
            } else {
                throw new HttpException("Unsuccessful request -------->  The response is statusCode= " + statusCode + " and message= " + result);
            }
        } finally {
            httpClient.close();
        }
    }

    private static DefaultHttpClient createHttpClient(int soTimeout) {
        if (soTimeout == 0) {
            soTimeout = CONNECTION_TIME_OUT;
        }
        try {
            HttpParams params = new BasicHttpParams();
            HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
            HttpProtocolParams.setContentCharset(params, HTTP.DEFAULT_CONTENT_CHARSET);
            HttpProtocolParams.setUseExpectContinue(params, true);
            // 设置超时时间
            params.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, soTimeout);
            // 读取超时
            params.setParameter(CoreConnectionPNames.SO_TIMEOUT, soTimeout);
            params.setParameter("Connection", "Keep-Alive");
            params.setParameter("Content-Length", " 12");

            KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
            trustStore.load(null, null);
            MySSLSocketFactory sf = new MySSLSocketFactory(trustStore);
            sf.setHostnameVerifier(MySSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

            SchemeRegistry registry = new SchemeRegistry();
            registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
            registry.register(new Scheme("https", sf, 443));
            ClientConnectionManager conMgr = new ThreadSafeClientConnManager(params, registry);

            return new DefaultHttpClient(conMgr, params);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static String sendHttpsPost(String url, String requestBody, String contentType, String hostName) throws Exception {
        log.info("httpsClient访问开始..." + url);
        CloseableHttpClient httpClient = null;
        try {
            SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
                // 默认信任所有证书
                public boolean isTrusted(X509Certificate[] arg0, String arg1) {
                    return false;
                }
            }).build();
            SSLConnectionSocketFactory ssf = new SSLConnectionSocketFactory(sslContext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
            httpClient = HttpClients.custom().setSSLSocketFactory(ssf).build();

            HttpPost httpPost = new HttpPost(url);
            Authenticator.setDefault(new MyAuthenticator("gaowei399","741asd#fg"));            
            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECTION_TIME_OUT).setSocketTimeout(READDATA_TIMEOUT)
                    .setProxy(new HttpHost("10.37.84.36", 8080))
                    .build();
            httpPost.setConfig(requestConfig);
            httpPost.setEntity(new StringEntity(requestBody, "UTF-8"));
            if (StringUtils.isNotBlank(hostName)) {
                httpPost.setHeader("HOST", hostName);
            }
            if (StringUtils.isNotBlank(contentType)) {
                httpPost.setHeader("Content-Type", contentType);
            }
            HttpResponse resp = httpClient.execute(httpPost);
            String result = EntityUtils.toString(resp.getEntity(), HTTP.UTF_8);
            int statusCode = resp.getStatusLine().getStatusCode();
            if (statusCode == HttpStatus.SC_OK) {
                return result;
            } else {
                throw new HttpException("HTTP REQUEST FAIL ---- statusCode: " + statusCode + " and result: " + result);
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw new RuntimeException("通讯未知系统异常", e);
        } finally {
            if (httpClient != null) {
                httpClient.close();
            }
        }
    }
}


/**
 * 过滤证书
 * 
 */
@SuppressWarnings("deprecation")
class MySSLSocketFactory extends SSLSocketFactory {
    SSLContext sslContext = SSLContext.getInstance("TLS");

    public MySSLSocketFactory(KeyStore truststore)
            throws NoSuchAlgorithmException, KeyManagementException,
            KeyStoreException, UnrecoverableKeyException {
        super(truststore);
        TrustManager tm = new X509TrustManager() {
            public void checkClientTrusted(X509Certificate[] chain,
                                           String authType) throws CertificateException {
            }

            public void checkServerTrusted(X509Certificate[] chain,
                                           String authType) throws CertificateException {
            }

            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        };
        sslContext.init(null, new TrustManager[]{tm}, null);
    }

    @Override
    public Socket createSocket(Socket socket, String host, int port,
                               boolean autoClose) throws IOException, UnknownHostException {
        return sslContext.getSocketFactory().createSocket(socket, host, port,
                autoClose);
    }

    @Override
    public Socket createSocket() throws IOException {
        return sslContext.getSocketFactory().createSocket();
    }
}
 

05-10 02:02