yujian
2019-09-05 e9a3f108de4f79fe6f246cd30f4427fc6aad5450
utils/src/main/java/org/yeshi/utils/HttpUtil.java
@@ -9,8 +9,11 @@
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.security.KeyStore;
import java.util.Iterator;
import java.util.Map;
import javax.net.ssl.SSLContext;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
@@ -24,6 +27,7 @@
import org.apache.commons.httpclient.methods.multipart.Part;
import org.apache.commons.httpclient.methods.multipart.StringPart;
import org.apache.commons.io.FileUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
@@ -31,6 +35,9 @@
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
@@ -533,4 +540,43 @@
      }
      return null;
   }
   @SuppressWarnings("deprecation")
   public static String httpsPost(String url, String body, String pwd, InputStream cert) throws Exception {
      String result = "";
      KeyStore keyStore = KeyStore.getInstance("PKCS12");
      InputStream instream = cert;
      try {
         keyStore.load(instream, pwd.toCharArray());
      } finally {
         instream.close();
      }
      // Trust own CA and all self-signed certs
      SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, pwd.toCharArray()).build();
      // Allow TLSv1 protocol only
      SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" }, null,
            SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
      CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
      try {
         HttpPost httppost = new HttpPost(url);
         httppost.setHeader("Content-Type", "text/html;charset=UTF-8");
         System.out.println("executing request" + httppost.getRequestLine());
         httppost.setEntity(new StringEntity(body, "UTF-8"));
         CloseableHttpResponse response = httpclient.execute(httppost);
         try {
            HttpEntity entity = response.getEntity();
            if (entity != null) {
               result = convertInputStreamToString(entity.getContent());
            }
            EntityUtils.consume(entity);
         } finally {
            response.close();
         }
      } finally {
         httpclient.close();
      }
      return result;
   }
}