欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2024-02-28 14:38:34
使用httpclient无需证书调用https的url地址,传输字节流。 复制代码 代码如下:package com.paic.hmreport.metaq; impo...

使用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();
  }
 }

}