欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

使用httpclient無需證書調(diào)用https的示例(java調(diào)用https)

 更新時間:2014年04月23日 09:30:22   作者:  
這篇文章主要介紹了使用httpclient無需證書調(diào)用https的示例(java調(diào)用https),需要的朋友可以參考下

使用httpclient無需證書調(diào)用https的url地址,傳輸字節(jié)流。

復(fù)制代碼 代碼如下:

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("客戶端調(diào)用失敗:" + e.getMessage());
   throw new RuntimeException("https調(diào)用失??!");
  }
  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;

  // 將請求參數(shù)封裝成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();
  }
 }

}

相關(guān)文章

  • Java之實現(xiàn)十進(jìn)制與十六進(jìn)制轉(zhuǎn)換案例講解

    Java之實現(xiàn)十進(jìn)制與十六進(jìn)制轉(zhuǎn)換案例講解

    這篇文章主要介紹了Java之實現(xiàn)十進(jìn)制與十六進(jìn)制轉(zhuǎn)換案例講解,本篇文章通過簡要的案例,講解了該項技術(shù)的了解與使用,以下就是詳細(xì)內(nèi)容,需要的朋友可以參考下
    2021-08-08
  • 超詳細(xì)講解SpringBoot參數(shù)校驗實例

    超詳細(xì)講解SpringBoot參數(shù)校驗實例

    經(jīng)常需要提供接口與用戶交互(獲取數(shù)據(jù)、上傳數(shù)據(jù)等),由于這個過程需要用戶進(jìn)行相關(guān)的操作,為了避免出現(xiàn)一些錯誤的數(shù)據(jù)等,一般需要對數(shù)據(jù)進(jìn)行校驗,下面這篇文章主要給大家介紹了關(guān)于SpringBoot各種參數(shù)校驗的相關(guān)資料,需要的朋友可以參考下
    2022-05-05
  • Java文件讀寫IO/NIO及性能比較詳細(xì)代碼及總結(jié)

    Java文件讀寫IO/NIO及性能比較詳細(xì)代碼及總結(jié)

    這篇文章主要介紹了Java文件讀寫IO/NIO及性能比較詳細(xì)代碼及總結(jié),具有一定借鑒價值,需要的朋友可以參考下。
    2017-12-12
  • Java8中Stream的一些神操作

    Java8中Stream的一些神操作

    Stream是Java8中處理集合的關(guān)鍵抽象概念,它可以指定你希望對集合進(jìn)行的操作,可以執(zhí)行非常復(fù)雜的查找、過濾和映射數(shù)據(jù)等操作,這篇文章主要給大家介紹了Java8中Stream的一些神操作,需要的朋友可以參考下
    2021-11-11
  • Java設(shè)計模式中的建造者(Builder)模式解讀

    Java設(shè)計模式中的建造者(Builder)模式解讀

    這篇文章主要介紹了Java設(shè)計模式中的建造者(Builder)模式解讀, 建造者模式是一種創(chuàng)建對象的設(shè)計模式,它通過將對象的構(gòu)建過程分解為多個步驟,并使用一個建造者類來封裝這些步驟,從而使得對象的構(gòu)建過程更加靈活和可擴(kuò)展,需要的朋友可以參考下
    2023-10-10
  • Java程序測試上傳Maven工程代碼示例解析

    Java程序測試上傳Maven工程代碼示例解析

    這篇文章主要介紹了Java程序測試上傳Maven工程代碼示例解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2020-08-08
  • Java開發(fā)框架spring實現(xiàn)自定義緩存標(biāo)簽

    Java開發(fā)框架spring實現(xiàn)自定義緩存標(biāo)簽

    這篇文章主要介紹了Java開發(fā)框架spring實現(xiàn)自定義緩存標(biāo)簽的詳細(xì)代碼,感興趣的小伙伴們可以參考一下
    2015-12-12
  • java.lang.UnsupportedClassVersionError錯誤的解決辦法(附圖文)

    java.lang.UnsupportedClassVersionError錯誤的解決辦法(附圖文)

    這篇文章主要給大家介紹了關(guān)于java.lang.UnsupportedClassVersionError錯誤的解決辦法,"java.lang.UnsupportedClassVersionError"意味著您正在運行的Java版本與編譯該類時使用的Java版本不兼容,需要的朋友可以參考下
    2023-10-10
  • SpringMVC框架的介紹與使用詳解

    SpringMVC框架的介紹與使用詳解

    SpringMVC?是一種基于?Java?的實現(xiàn)?MVC?設(shè)計模型的請求驅(qū)動類型的輕量級?Web?框架,跟Spring,Mybatis框架并稱為ssm,這篇文章主要介紹了SpringMVC框架的介紹與使用,需要的朋友可以參考下
    2022-08-08
  • 使用java swing實現(xiàn)qq登錄界面示例分享

    使用java swing實現(xiàn)qq登錄界面示例分享

    這篇文章主要介紹了使用java swing實現(xiàn)qq登錄界面示例,需要的朋友可以參考下
    2014-04-04

最新評論