使用httpclient怎么實現(xiàn)https,相信很多沒有經(jīng)驗的人對此束手無策,為此本文總結(jié)了問題出現(xiàn)的原因和解決方法,通過這篇文章希望你能解決這個問題。
成都創(chuàng)新互聯(lián)專業(yè)為企業(yè)提供三水網(wǎng)站建設(shè)、三水做網(wǎng)站、三水網(wǎng)站設(shè)計、三水網(wǎng)站制作等企業(yè)網(wǎng)站建設(shè)、網(wǎng)頁設(shè)計與制作、三水企業(yè)網(wǎng)站模板建站服務(wù),10年三水做網(wǎng)站經(jīng)驗,不只是建網(wǎng)站,更提供有價值的思路和整體網(wǎng)絡(luò)服務(wù)。
package com.neusoft.sample.opscopereq;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.security.KeyStore;
import java.security.SecureRandom;
import java.security.cert.CertificateFactory;
import java.util.Base64;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManagerFactory;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import com.alibaba.fastjson.JSONObject;
public class M {
public static void main(String[] args) throws Exception {
InputStream inputStream = M.class.getClassLoader().getResourceAsStream("sssssss.crt");
CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
keyStore.load(null);
String certificateAlias = Integer.toString(0);
keyStore.setCertificateEntry(certificateAlias, certificateFactory.generateCertificate(inputStream));
inputStream.close();
SSLContext sslContext = SSLContext.getInstance("TLS");
TrustManagerFactory trustManagerFactory = TrustManagerFactory
.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init(keyStore);
sslContext.init(null, trustManagerFactory.getTrustManagers(), new SecureRandom());
CloseableHttpClient client = HttpClients.custom().setSSLContext(sslContext).setSSLHostnameVerifier(new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) {
// TODO Auto-generated method stub
return true;
}
}) .build();
HttpPost http = new HttpPost("www.url.com");
String USERNAME = "user";
String PASSWORD = "psw";
String auth = USERNAME + ":" + PASSWORD;
byte[] encodedAuth = Base64.getEncoder().encode(auth.getBytes(Charset.forName("US-ASCII")));
String AUTH_HEADER_VAL = "Basic " + new String(encodedAuth);
http.setHeader("Authorization", AUTH_HEADER_VAL);
JSONObject paramObj = new JSONObject();
paramObj.put("industryCode", "517");
paramObj.put("keyWord", "批發(fā)");
paramObj.put("pageNum", 1);
HttpEntity entity=new StringEntity(paramObj.toJSONString(), "application/json;", "utf-8");
http.setEntity(entity);
CloseableHttpResponse res = client.execute(http);
String aa = EntityUtils.toString( res.getEntity() );
System.out.println(aa);
}
}
看完上述內(nèi)容,你們掌握使用httpclient怎么實現(xiàn)https的方法了嗎?如果還想學到更多技能或想了解更多相關(guān)內(nèi)容,歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,感謝各位的閱讀!