使用httpclient无需证书调用https的示例(java调用https)

 更新时间:2014年04月23日 09:30:22   作者:  
这篇文章主要介绍了使用httpclient无需证书调用https的示例(java调用https),需要的朋友可以参考下

使用httpclient无需证书调用https的url地址,传输字节流。

复制代码 代码如下:

package com.paic.hmreport.metaQ;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.NoSuchAlgorithmException;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManagerFactory;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.BufferedHttpEntity;
import org.apache.http.entity.InputStreamEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class HttpsClient {

 public static Log log = LogFactory.getLog(HttpsClient.class);

 /* for windows */

 /* for linux */
 /*
  * private static String CLIENT_CERT_PWD="123456"; private static String
  * TRUST_CERT_PATH=
  * "/wls/bis_emulator/apps/emulator/config/cert/BIS_FRONT_SERVER_STG_BY_ZXC.jks"
  * ; private static String TRUST_CERT_PWD="123456"; private static String
  * client_cert_path=
  * "/wls/bis_emulator/apps/emulator/config/cert/EXV_GROUP_EAI_B2B_ZUCHE_100.jks"
  * ;
  */

 /**
  * @param args
  * @throws IOException
  * @throws ClientProtocolException
  * @throws NoSuchAlgorithmException
  * @throws KeyManagementException
  */
 public static void main(String[] args) throws KeyManagementException,
   NoSuchAlgorithmException, ClientProtocolException, IOException {
  // sendMsgOfCert("https://10.25.32.13:8007", "hello world", "123456",
  // "kserver.jks", "123456", "tclient.jks");
  send(
    "https://127.0.0.1/hmreport/messageChannel.ac?sign=TEZrSHZJdDNrRFNIb0M0QnJrc3VIdDBJWDRYTTVXZGJYZHlLUkpxQlp6anQyYUJITEpSVWQzOWh4b0RvOW96TGVvN2ZhWEJ3SkZvN0JIZVhhOFRuaWZLY3VwbDExSjg2cjZFMFFvNHV4YktJd3E0T2RvTmVhQzV6NVhNTzJLN1NaNWpoUUhTVTR0NTNEdWFOVHpuZjh1ajA0VUhqaFBWRTJvM0s2dnEyTFVnPQ==",
    "Helloworld!");
 }

 public static String sendMsgOfCert(String urlString, String requestData,
   String CLIENT_CERT_PWD, String CLIENT_CERT_PATH,
   String TRUST_CERT_PWD, String TRUST_CERT_PATH) {
  StringBuffer sb = null;
  try {

   log.info("开始初始化https客户端!");
   SSLContext sslContext = SSLContext.getInstance("SSL");

   KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
   TrustManagerFactory tmf = TrustManagerFactory
     .getInstance("SunX509");

   KeyStore ks = KeyStore.getInstance("JKS");
   ks.load(ClassLoader.getSystemResourceAsStream(CLIENT_CERT_PATH),
     CLIENT_CERT_PWD.toCharArray());
   kmf.init(ks, CLIENT_CERT_PWD.toCharArray());

   KeyStore tks = KeyStore.getInstance("JKS");
   tks.load(ClassLoader.getSystemResourceAsStream(TRUST_CERT_PATH),
     TRUST_CERT_PWD.toCharArray());

   tmf.init(tks);
   sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);

   HostnameVerifier hostnameVerifier = new HostnameVerifier() {
    public boolean verify(String arg0, SSLSession arg1) {
     return true;
    }
   };
   HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);

   // URL url = new URL("https://172.40.1.83:8007");
   URL url = new URL(urlString);
   HttpsURLConnection urlCon = (HttpsURLConnection) url
     .openConnection();
   urlCon.setDoOutput(true);
   urlCon.setDoInput(true);
   urlCon.setRequestMethod("POST");
   urlCon.setRequestProperty("Content-type",
     "text/xml;charset=GB18030");
   urlCon.setSSLSocketFactory(sslContext.getSocketFactory());

   OutputStream os = urlCon.getOutputStream();
   InputStream fis = new ByteArrayInputStream(requestData
     .getBytes("GB18030"));
   BufferedInputStream bis = new BufferedInputStream(fis);
   byte[] bytes = new byte[1024];
   int len = -1;
   while ((len = bis.read(bytes)) != -1) {
    os.write(bytes, 0, len);
   }
   os.flush();
   bis.close();
   fis.close();
   os.close();

   InputStream is = urlCon.getInputStream();
   BufferedReader br = new BufferedReader(new InputStreamReader(is,
     "GB18030"));
   // DataInputStream indata = new DataInputStream(is);
   // String ret = "";
   // String str_return = "";
   // while (ret != null) {
   // ret = indata.readLine();
   // if (ret != null && !ret.trim().equals("")) {
   // str_return = str_return
   // + new String(ret.getBytes("ISO-8859-1"), "GBK");
   // }
   // }
   // System.out.println("str_return:" + str_return);
   // System.out.println("br.readLine():"+new
   // String(br.readLine().getBytes("GBK"), "GBK"));
   sb = new StringBuffer();
   String line;
   while ((line = br.readLine()) != null) {
    sb.append(line);
   }
   System.out.println("sb:" + sb);

   br.close();
   is.close();
   urlCon.disconnect();
  } catch (Exception e) {
   e.fillInStackTrace();
   log.info("客户端调用失败:" + e.getMessage());
   throw new RuntimeException("https调用失败!");
  }
  return null;
 }

 public static void send(String requsetString, String requestData)
   throws NoSuchAlgorithmException, KeyManagementException,
   ClientProtocolException, IOException {
  // First create a trust manager that won't care.
  X509TrustManager trustManager = new X509TrustManager() {
   public void checkClientTrusted(X509Certificate[] chain,
     String authType) throws CertificateException {
    // Don't do anything.
   }

   public void checkServerTrusted(X509Certificate[] chain,
     String authType) throws CertificateException {
    // Don't do anything.
   }

   public X509Certificate[] getAcceptedIssuers() {
    // Don't do anything.
    return null;
   }

  };
  // Now put the trust manager into an SSLContext.
  SSLContext sslcontext = SSLContext.getInstance("SSL");
  sslcontext.init(null, new TrustManager[] { trustManager }, null);

  // Use the above SSLContext to create your socket factory
  // (I found trying to extend the factory a bit difficult due to a
  // call to createSocket with no arguments, a method which doesn't
  // exist anywhere I can find, but hey-ho).
  SSLSocketFactory sf = new SSLSocketFactory(sslcontext);
  sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

  DefaultHttpClient httpclient = new DefaultHttpClient();
  httpclient.getConnectionManager().getSchemeRegistry().register(
    new Scheme("https", sf, 443));

  // String requset = "https://180.168.35.140/api/vm.list";
  HttpPost httpPost = new HttpPost(requsetString);
  String result = "";
  // Execute HTTP request
  httpPost.setHeader("Authorization", "basic "
    + "dGNsb3VkYWRtaW46dGNsb3VkMTIz");
  httpPost.setHeader("Content-type", "application/xml");

  StringEntity reqEntity;

  // 将请求参数封装成HttpEntity
  reqEntity = new StringEntity(requestData);
  BufferedHttpEntity bhe = new BufferedHttpEntity(reqEntity);
  httpPost.setEntity(bhe);
  HttpResponse response = httpclient.execute(httpPost);
  HttpEntity resEntity = response.getEntity();
  InputStreamReader reader = new InputStreamReader(resEntity.getContent());

  char[] buff = new char[1024];
  int length = 0;
  while ((length = reader.read(buff)) != -1) {
   result += new String(buff, 0, length);
  }
  httpclient.getConnectionManager().shutdown();

  System.out.println(">>>:" + result);
 }

 public static void test() {
  String words = "hello";
  try {

   FileOutputStream out = new FileOutputStream("D:/file.txt");
   out.write(words.getBytes());
   out.flush();
   out.close();
  } catch (Exception e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }

}

相关文章

  • Java之实现十进制与十六进制转换案例讲解

    Java之实现十进制与十六进制转换案例讲解

    这篇文章主要介绍了Java之实现十进制与十六进制转换案例讲解,本篇文章通过简要的案例,讲解了该项技术的了解与使用,以下就是详细内容,需要的朋友可以参考下
    2021-08-08
  • 超详细讲解SpringBoot参数校验实例

    超详细讲解SpringBoot参数校验实例

    经常需要提供接口与用户交互(获取数据、上传数据等),由于这个过程需要用户进行相关的操作,为了避免出现一些错误的数据等,一般需要对数据进行校验,下面这篇文章主要给大家介绍了关于SpringBoot各种参数校验的相关资料,需要的朋友可以参考下
    2022-05-05
  • Java文件读写IO/NIO及性能比较详细代码及总结

    Java文件读写IO/NIO及性能比较详细代码及总结

    这篇文章主要介绍了Java文件读写IO/NIO及性能比较详细代码及总结,具有一定借鉴价值,需要的朋友可以参考下。
    2017-12-12
  • Java8中Stream的一些神操作

    Java8中Stream的一些神操作

    Stream是Java8中处理集合的关键抽象概念,它可以指定你希望对集合进行的操作,可以执行非常复杂的查找、过滤和映射数据等操作,这篇文章主要给大家介绍了Java8中Stream的一些神操作,需要的朋友可以参考下
    2021-11-11
  • Java设计模式中的建造者(Builder)模式解读

    Java设计模式中的建造者(Builder)模式解读

    这篇文章主要介绍了Java设计模式中的建造者(Builder)模式解读, 建造者模式是一种创建对象的设计模式,它通过将对象的构建过程分解为多个步骤,并使用一个建造者类来封装这些步骤,从而使得对象的构建过程更加灵活和可扩展,需要的朋友可以参考下
    2023-10-10
  • Java程序测试上传Maven工程代码示例解析

    Java程序测试上传Maven工程代码示例解析

    这篇文章主要介绍了Java程序测试上传Maven工程代码示例解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-08-08
  • Java开发框架spring实现自定义缓存标签

    Java开发框架spring实现自定义缓存标签

    这篇文章主要介绍了Java开发框架spring实现自定义缓存标签的详细代码,感兴趣的小伙伴们可以参考一下
    2015-12-12
  • java.lang.UnsupportedClassVersionError错误的解决办法(附图文)

    java.lang.UnsupportedClassVersionError错误的解决办法(附图文)

    这篇文章主要给大家介绍了关于java.lang.UnsupportedClassVersionError错误的解决办法,"java.lang.UnsupportedClassVersionError"意味着您正在运行的Java版本与编译该类时使用的Java版本不兼容,需要的朋友可以参考下
    2023-10-10
  • SpringMVC框架的介绍与使用详解

    SpringMVC框架的介绍与使用详解

    SpringMVC 是一种基于 Java 的实现 MVC 设计模型的请求驱动类型的轻量级 Web 框架,跟Spring,Mybatis框架并称为ssm,这篇文章主要介绍了SpringMVC框架的介绍与使用,需要的朋友可以参考下
    2022-08-08
  • 使用java swing实现qq登录界面示例分享

    使用java swing实现qq登录界面示例分享

    这篇文章主要介绍了使用java swing实现qq登录界面示例,需要的朋友可以参考下
    2014-04-04

最新评论