فهرست منبع

整理hos-rest中的EHRHttpHelper

Airhead 8 سال پیش
والد
کامیت
b7f9feb096
1فایلهای تغییر یافته به همراه25 افزوده شده و 182 حذف شده
  1. 25 182
      hos-rest/src/main/java/com/yihu/hos/rest/common/http/EHRHttpHelper.java

+ 25 - 182
hos-rest/src/main/java/com/yihu/hos/rest/common/http/EHRHttpHelper.java

@ -3,41 +3,27 @@ package com.yihu.hos.rest.common.http;
import com.yihu.hos.core.datatype.StringUtil;
import com.yihu.hos.core.http.HTTPResponse;
import com.yihu.hos.core.http.HttpClientKit;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.client.entity.GzipDecompressingEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.entity.ContentType;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.EncodedResource;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import javax.net.ssl.SSLContext;
import java.io.*;
import java.io.File;
import java.util.Map;
import java.util.Properties;
import java.util.zip.GZIPInputStream;
//TODO:对于Basic认证内容,暂时未验证,可以使用http://user@password:host的方式尝试访问
public class EHRHttpHelper {
    public static String defaultHttpUrl;
    public static String clientId;
    public static String clientKey;
    private static String defaultPropertiesPath = "config/http.properties";
    private static SSLConnectionSocketFactory defaultSSL;
    private static String defaultHttpUser;
    private static String defaultHttpPassword;
    static {
        //默认配置
        try {
            final String defaultPropertiesPath = "config/http.properties";
            Resource resource = new ClassPathResource(defaultPropertiesPath);
            EncodedResource encRes = new EncodedResource(resource, "UTF-8");
            Properties props = PropertiesLoaderUtils.loadProperties(encRes);
@ -55,17 +41,11 @@ public class EHRHttpHelper {
                // sslKeystore = homeUrl + "tomcat.keystore";
                sslKeystore = "E://tomcat.keystore";
            }
            if (sslKeystore != null && sslKeystore.length() > 0 && sslPassword != null && sslPassword.length() > 0) {
                SSLContext sslContext = SSLContexts.custom()
                        .loadTrustMaterial(new File(sslKeystore), sslPassword.toCharArray(),
                                new TrustSelfSignedStrategy())
                        .build();
                defaultSSL = new SSLConnectionSocketFactory(
                        sslContext,
                        new String[]{"TLSv1"},
                        null,
                        SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
            if (sslKeystore.length() > 0 && sslPassword != null && sslPassword.length() > 0) {
                HttpClientKit.addKeyStore(defaultHttpUrl, sslKeystore, sslPassword);
            }
        } catch (Exception e) {
            System.out.print(e.getMessage());
        }
@ -76,7 +56,7 @@ public class EHRHttpHelper {
     * Get方法
     ******************************************/
    public static HTTPResponse get(String url) {
        return get(url, null, null);
        return get(url, null);
    }
    public static HTTPResponse get(String url, Map<String, String> params) {
@ -84,28 +64,18 @@ public class EHRHttpHelper {
    }
    public static HTTPResponse get(String url, Map<String, String> params, Map<String, String> header) {
        if (url.startsWith("https")) {
            return get(url, params, header, defaultSSL);
        } else {
            //默认http不走ssl和用户密码
            return get(url, params, header, null, null, null);
        }
        return get(url, params, header, false);
    }
    public static HTTPResponse get(String url, Map<String, String> params, Map<String, String> header, Boolean isCheck) {
        if (isCheck) {
            return get(url, params, header, defaultSSL, defaultHttpUser, defaultHttpPassword);
            return get(url, params, header, defaultHttpUser, defaultHttpPassword);
        } else {
            return get(url, params, header, null, null, null);
            return get(url, params, header, null, null);
        }
    }
    public static HTTPResponse get(String url, Map<String, String> params, Map<String, String> header, SSLConnectionSocketFactory ssl) {
        return get(url, params, header, ssl, defaultHttpUser, defaultHttpPassword);
    }
    public static HTTPResponse get(String url, Map<String, String> params, Map<String, String> header, SSLConnectionSocketFactory ssl, String user, String password) {
    public static HTTPResponse get(String url, Map<String, String> params, Map<String, String> header, String user, String password) {
        return HttpClientKit.request("GET", url, params, header);
    }
@ -113,7 +83,7 @@ public class EHRHttpHelper {
     * Post方法
     ******************************************/
    public static HTTPResponse post(String url) {
        return post(url, null, null);
        return post(url, null);
    }
    public static HTTPResponse post(String url, Map<String, String> params) {
@ -121,27 +91,18 @@ public class EHRHttpHelper {
    }
    public static HTTPResponse post(String url, Map<String, String> params, Map<String, String> header) {
        if (url.startsWith("https")) {
            return post(url, params, header, defaultSSL);
        } else {
            //默认http不走ssl和用户密码
            return post(url, params, header, null, null, null);
        }
        return post(url, params, header, false);
    }
    public static HTTPResponse post(String url, Map<String, String> params, Map<String, String> header, Boolean isCheck) {
        if (isCheck) {
            return post(url, params, header, defaultSSL, defaultHttpUser, defaultHttpPassword);
            return post(url, params, header, defaultHttpUser, defaultHttpPassword);
        } else {
            return post(url, params, header, null, null, null);
            return post(url, params, header, null, null);
        }
    }
    public static HTTPResponse post(String url, Map<String, String> params, Map<String, String> header, SSLConnectionSocketFactory ssl) {
        return post(url, params, header, ssl, defaultHttpUser, defaultHttpPassword);
    }
    public static HTTPResponse post(String url, Map<String, String> params, Map<String, String> header, SSLConnectionSocketFactory ssl, String user, String password) {
    public static HTTPResponse post(String url, Map<String, String> params, Map<String, String> header, String user, String password) {
        return HttpClientKit.request("POST", url, params, header);
    }
@ -175,28 +136,18 @@ public class EHRHttpHelper {
    }
    public static HTTPResponse put(String url, Map<String, String> params, Map<String, String> header) {
        if (url.startsWith("https")) {
            return put(url, params, header, defaultSSL);
        } else {
            //默认http不走ssl和用户密码
            return put(url, params, header, null, null, null);
        }
        return put(url, params, header, false);
    }
    public static HTTPResponse put(String url, Map<String, String> params, Map<String, String> header, Boolean isCheck) {
        if (isCheck) {
            return put(url, params, header, defaultSSL, defaultHttpUser, defaultHttpPassword);
            return put(url, params, header, defaultHttpUser, defaultHttpPassword);
        } else {
            return put(url, params, header, null, null, null);
            return put(url, params, header, null, null);
        }
    }
    public static HTTPResponse put(String url, Map<String, String> params, Map<String, String> header, SSLConnectionSocketFactory ssl) {
        return put(url, params, header, ssl, defaultHttpUser, defaultHttpPassword);
    }
    public static HTTPResponse put(String url, Map<String, String> params, Map<String, String> header, SSLConnectionSocketFactory ssl, String user, String password) {
    public static HTTPResponse put(String url, Map<String, String> params, Map<String, String> header, String user, String password) {
        return HttpClientKit.request("PUT", url, params, header);
    }
@ -212,127 +163,19 @@ public class EHRHttpHelper {
    }
    public static HTTPResponse delete(String url, Map<String, String> params, Map<String, String> header) {
        if (url.startsWith("https")) {
            return delete(url, params, header, defaultSSL);
        } else {
            //默认http不走ssl和用户密码
            return delete(url, params, header, null, null, null);
        }
        return delete(url, params, header, false);
    }
    public static HTTPResponse delete(String url, Map<String, String> params, Map<String, String> header, Boolean isCheck) {
        if (isCheck) {
            return delete(url, params, header, defaultSSL, defaultHttpUser, defaultHttpPassword);
            return delete(url, params, header, defaultHttpUser, defaultHttpPassword);
        } else {
            return delete(url, params, header, null, null, null);
            return delete(url, params, header, null, null);
        }
    }
    public static HTTPResponse delete(String url, Map<String, String> params, Map<String, String> header, SSLConnectionSocketFactory ssl) {
        return delete(url, params, header, ssl, defaultHttpUser, defaultHttpPassword);
    }
    public static HTTPResponse delete(String url, Map<String, String> params, Map<String, String> header, SSLConnectionSocketFactory ssl, String user, String password) {
    public static HTTPResponse delete(String url, Map<String, String> params, Map<String, String> header, String user, String password) {
        return HttpClientKit.request("DELETE", url, params, header);
    }
    public static String getWebPage(String url) {
        String returnString = "";
        HTTPResponse re = new HTTPResponse(200, "");
        CloseableHttpResponse response = null;
        CloseableHttpClient httpclient = HttpClients.custom()
                .setSSLSocketFactory(defaultSSL)
                .build();
        //设置请求信息
        try {
            HttpGet httpGet = new HttpGet(url);
            response = httpclient.execute(httpGet);
            String line;
            // 读取输入流的数据,并显示
            HttpEntity httpEntity = response.getEntity();
            Header header = response.getEntity().getContentEncoding();
            if (httpEntity.getContentLength() < 2147483647L) {            //EntityUtils无法处理ContentLength超过2147483647L的Entity
                if (header != null && "gzip".equals(header.getValue())) {
                    returnString = EntityUtils.toString(new GzipDecompressingEntity(httpEntity));
                } else {
                    returnString = EntityUtils.toString(httpEntity);
                }
            } else {
                InputStream in = httpEntity.getContent();
                if (header != null && "gzip".equals(header.getValue())) {
                    returnString = unZip(in, ContentType.getOrDefault(httpEntity).getCharset().toString());
                } else {
                    returnString = readInStreamToString(in, ContentType.getOrDefault(httpEntity).getCharset().toString());
                }
                if (in != null) {
                    in.close();
                }
            }
        } catch (Exception e) {
            re = new HTTPResponse(201, e.getMessage());
            e.printStackTrace();
        } finally {
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        System.out.println(returnString);
        return returnString;
    }
    /**
     * 解压服务器返回的gzip流
     *
     * @param in      抓取返回的InputStream流
     * @param charSet 页面内容编码
     * @return 页面内容的String格式
     * @throws IOException
     */
    private static String unZip(InputStream in, String charSet) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        GZIPInputStream gis = null;
        try {
            gis = new GZIPInputStream(in);
            byte[] _byte = new byte[1024];
            int len = 0;
            while ((len = gis.read(_byte)) != -1) {
                baos.write(_byte, 0, len);
            }
            String unzipString = new String(baos.toByteArray(), charSet);
            return unzipString;
        } finally {
            if (gis != null) {
                gis.close();
            }
            if (baos != null) {
                baos.close();
            }
        }
    }
    /**
     * 读取InputStream流
     *
     * @param in InputStream流
     * @return 从流中读取的String
     * @throws IOException
     */
    private static String readInStreamToString(InputStream in, String charSet) throws IOException {
        StringBuilder str = new StringBuilder();
        String line;
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in, charSet));
        while ((line = bufferedReader.readLine()) != null) {
            str.append(line);
            str.append("\n");
        }
        if (bufferedReader != null) {
            bufferedReader.close();
        }
        return str.toString();
    }
}