使用httpclient無需證書調(diào)用https的示例(java調(diào)用https)
使用httpclient無需證書調(diào)用https的url地址,傳輸字節(jié)流。
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;
// 將請(qǐng)求參數(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();
}
}
}
- Java HttpClient技術(shù)詳解
- Java 使用 HttpClient 發(fā)送 GET請(qǐng)求和 POST請(qǐng)求
- Java httpClient連接池支持多線程高并發(fā)的實(shí)現(xiàn)
- Java利用httpclient通過get、post方式調(diào)用https接口的方法
- Java httpClient介紹以及使用示例
- JAVA利用HttpClient進(jìn)行POST請(qǐng)求(HTTPS)實(shí)例
- 使用java的HttpClient實(shí)現(xiàn)多線程并發(fā)
- Java利用HttpClient模擬POST表單操作應(yīng)用及注意事項(xiàng)
- java實(shí)現(xiàn)HttpClient異步請(qǐng)求資源的方法
- Java使用HttpClient詳細(xì)示例
相關(guān)文章
SpringCloud遠(yuǎn)程服務(wù)調(diào)用實(shí)戰(zhàn)筆記
本文給大家介紹SpringCloud遠(yuǎn)程服務(wù)調(diào)用實(shí)戰(zhàn)筆記,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友參考下吧2021-11-11
生產(chǎn)環(huán)境jvm常用的參數(shù)設(shè)置建議分享
在Java應(yīng)用程序的部署過程中,合理配置JVM(Java虛擬機(jī))參數(shù)對(duì)于提升應(yīng)用性能、穩(wěn)定性和資源利用效率至關(guān)重要,本文將探討一些常用的JVM參數(shù)設(shè)置建議,幫助開發(fā)者在生產(chǎn)環(huán)境中優(yōu)化Java應(yīng)用,需要的朋友可以參考下2025-04-04
數(shù)組實(shí)現(xiàn)Java 自定義Queue隊(duì)列及應(yīng)用操作
這篇文章主要介紹了數(shù)組實(shí)現(xiàn)Java 自定義Queue隊(duì)列及應(yīng)用操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-06-06
Springboot如何添加server.servlet.context-path相關(guān)使用
這篇文章主要介紹了Springboot如何添加server.servlet.context-path相關(guān)使用問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-03-03
詳細(xì)聊一聊java語言中的package和import機(jī)制
這篇文章主要給大家介紹了關(guān)于java語言中package和import機(jī)制的相關(guān)資料,Java中的package是指將相關(guān)的類組織在一起的一種機(jī)制,它可以用來避免命名沖突,也可以方便地管理和維護(hù)代碼,需要的朋友可以參考下2024-01-01
Java使用正則表達(dá)式判斷獨(dú)立字符的存在(代碼示例)
通過使用正則表達(dá)式,我們可以更加靈活地判斷字符串中是否包含特定的字符,并且可以控制匹配的條件,如獨(dú)立的字符,這為我們處理字符串提供了更多的選擇和功能,這篇文章主要介紹了Java使用正則表達(dá)式判斷獨(dú)立字符的存在,需要的朋友可以參考下2023-10-10
java開源好用的簡(jiǎn)繁轉(zhuǎn)換類庫(kù)推薦
這篇文章主要為大家介紹了java開源好用的簡(jiǎn)繁轉(zhuǎn)換類庫(kù)推薦,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-08-08

