CloseableHttpClient載入認證來訪問https網站

來源:互聯網
上載者:User
對安全性有要求的網站一般使用https來加密傳輸的請求和響應。https離不開認證,關於認證不在多說。Apache的HttpClient支援https,

下面是官方的範例程式,程式中使用了my.store這個檔案,

這個檔案不是網站的認證,而是一份包含自己密碼的自己的認證庫。這個檔案是需要自己產生的,使用jdk中的keytool命令可以很方便的產生my.store檔案。步驟如下(以支付寶為例):

瀏覽器(以chrome為例)訪問https://www.alipay.com/,點擊網域名稱左側的小鎖,可以查看支付寶的認證資訊


將支付包的認證資訊匯出,認證格式有很多中,der、cer等。隨便選擇即可。

命令列或者shell執行 keytool     -import -alias "my alipay cert" -file www.alipay.com.cert     -keystore my.store,

如果keytool命令不識別,去檢查一下jdk的環境變數是否設定正確。”my alipay cert”是個別名,隨便取。“www.alipay.com.cert”這個檔案就是從瀏覽器中匯出的支付寶的認證。

“my.store”是產生的自己 的認證庫檔案。斷行符號執行,效果如下:

OK,現在可以執行下面的代碼了:

[java]  view plain  copy package com.yeetrack.httpclient;         /**       * Created with IntelliJ IDEA.       * User: victor       * Date: 13-10-11       * Time: 下午3:09       * To change this template use File | Settings | File Templates.       */         import java.io.File;         import java.io.FileInputStream;         import java.security.KeyStore;         import javax.net.ssl.SSLContext;         import org.apache.http.HttpEntity;         import org.apache.http.client.methods.CloseableHttpResponse;         import org.apache.http.client.methods.HttpGet;         import org.apache.http.conn.ssl.SSLContexts;         import org.apache.http.conn.ssl.SSLConnectionSocketFactory;         import org.apache.http.impl.client.CloseableHttpClient;         import org.apache.http.impl.client.HttpClients;         import org.apache.http.util.EntityUtils;               /**       * 代碼展示了如果使用ssl context建立安全socket串連       */         public class ClientCustomSSL {             public final static void main(String[] args) throws Exception {       &nbs

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.