Java https請求 HttpsURLConnection

有關(guān)tomcat 6.0如何配置https服務的文章可以參考:http://blog.csdn.net/zhou_zion/article/details/6759171
以下主要講解如何使用https發(fā)起post請求:
參考文檔:梁棟前輩的《Java加密與解密的藝術(shù)》

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.GeneralSecurityException;
import java.security.KeyStore;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;

public class HttpsPost {
    /**
     * 獲得KeyStore.
     * @param keyStorePath
     *            密鑰庫路徑
     * @param password
     *            密碼
     * @return 密鑰庫
     * @throws Exception
     */
    public static KeyStore getKeyStore(String password, String keyStorePath)
            throws Exception {
        // 實例化密鑰庫
        KeyStore ks = KeyStore.getInstance("JKS");
        // 獲得密鑰庫文件流
        FileInputStream is = new FileInputStream(keyStorePath);
        // 加載密鑰庫
        ks.load(is, password.toCharArray());
        // 關(guān)閉密鑰庫文件流
        is.close();
        return ks;
    }

    /**
     * 獲得SSLSocketFactory.
     * @param password
     *            密碼
     * @param keyStorePath
     *            密鑰庫路徑
     * @param trustStorePath
     *            信任庫路徑
     * @return SSLSocketFactory
     * @throws Exception
     */
    public static SSLContext getSSLContext(String password,
            String keyStorePath, String trustStorePath) throws Exception {
        // 實例化密鑰庫
        KeyManagerFactory keyManagerFactory = KeyManagerFactory
                .getInstance(KeyManagerFactory.getDefaultAlgorithm());
        // 獲得密鑰庫
        KeyStore keyStore = getKeyStore(password, keyStorePath);
        // 初始化密鑰工廠
        keyManagerFactory.init(keyStore, password.toCharArray());

        // 實例化信任庫
        TrustManagerFactory trustManagerFactory = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        // 獲得信任庫
        KeyStore trustStore = getKeyStore(password, trustStorePath);
        // 初始化信任庫
        trustManagerFactory.init(trustStore);
        // 實例化SSL上下文
        SSLContext ctx = SSLContext.getInstance("TLS");
        // 初始化SSL上下文
        ctx.init(keyManagerFactory.getKeyManagers(),
                trustManagerFactory.getTrustManagers(), null);
        // 獲得SSLSocketFactory
        return ctx;
    }

    /**
     * 初始化HttpsURLConnection.
     * @param password
     *            密碼
     * @param keyStorePath
     *            密鑰庫路徑
     * @param trustStorePath
     *            信任庫路徑
     * @throws Exception
     */
    public static void initHttpsURLConnection(String password,
            String keyStorePath, String trustStorePath) throws Exception {
        // 聲明SSL上下文
        SSLContext sslContext = null;
        // 實例化主機名驗證接口
        HostnameVerifier hnv = new MyHostnameVerifier();
        try {
            sslContext = getSSLContext(password, keyStorePath, trustStorePath);
        } catch (GeneralSecurityException e) {
            e.printStackTrace();
        }
        if (sslContext != null) {
            HttpsURLConnection.setDefaultSSLSocketFactory(sslContext
                    .getSocketFactory());
        }
        HttpsURLConnection.setDefaultHostnameVerifier(hnv);
    }

    /**
     * 發(fā)送請求.
     * @param httpsUrl
     *            請求的地址
     * @param xmlStr
     *            請求的數(shù)據(jù)
     */
    public static void post(String httpsUrl, String xmlStr) {
        HttpsURLConnection urlCon = null;
        try {
            urlCon = (HttpsURLConnection) (new URL(httpsUrl)).openConnection();
            urlCon.setDoInput(true);
            urlCon.setDoOutput(true);
            urlCon.setRequestMethod("POST");
            urlCon.setRequestProperty("Content-Length",
                    String.valueOf(xmlStr.getBytes().length));
            urlCon.setUseCaches(false);
            //設置為gbk可以解決服務器接收時讀取的數(shù)據(jù)中文亂碼問題
            urlCon.getOutputStream().write(xmlStr.getBytes("gbk"));
            urlCon.getOutputStream().flush();
            urlCon.getOutputStream().close();
            BufferedReader in = new BufferedReader(new InputStreamReader(
                    urlCon.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                System.out.println(line);
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 測試方法.
     * @param args
     * @throws Exception
     */
    public static void main(String[] args) throws Exception {
        // 密碼
        String password = "123456";
        // 密鑰庫
        String keyStorePath = "tomcat.keystore";
        // 信任庫
        String trustStorePath = "tomcat.keystore";
        // 本地起的https服務
        String httpsUrl = "https://localhost:8443/service/httpsPost";
        // 傳輸文本
        String xmlStr = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><fruitShop><fruits><fruit><kind>蘿卜</kind></fruit><fruit><kind>菠蘿</kind></fruit></fruits></fruitShop>";
        HttpsPost.initHttpsURLConnection(password, keyStorePath, trustStorePath);
        // 發(fā)起請求
        HttpsPost.post(httpsUrl, xmlStr);
    }
}

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLSession;

/**
 * 實現(xiàn)用于主機名驗證的基接口朝抖。 
 * 在握手期間升熊,如果 URL 的主機名和服務器的標識主機名不匹配简烘,則驗證機制可以回調(diào)此接口的實現(xiàn)程序來確定是否應該允許此連接切揭。
 */
public class MyHostnameVerifier implements HostnameVerifier {
    @Override
    public boolean verify(String hostname, SSLSession session) {
        if("localhost".equals(hostname)){
            return true;
        } else {
            return false;
        }
    }
}

接收請求的Web應用:

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
    xmlns="http://java.sun.com/xml/ns/javaee" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
    http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  <servlet>
    <servlet-name>rollBack</servlet-name>
    <servlet-class>rollBack</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>rollBack</servlet-name>
    <url-pattern>/httpsPost</url-pattern>
  </servlet-mapping>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

rollBack servlet

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class rollBack extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //獲取請求流
        ServletInputStream sis = request.getInputStream();
        BufferedReader in = new BufferedReader(new InputStreamReader(sis));
        String line;
        if((line = in.readLine()) != null){
            System.out.println(line);
        }
        in.close();
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        this.doGet(request, response);
    }
}

使用apache的httpClient是一個最常用的開源的java第三方工具包
需要httpclent.jar
創(chuàng)建client的工具類

public static CloseableHttpClient createSSLClientDefault(){
try {
             SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
                 //信任所有
                 public boolean isTrusted(X509Certificate[] chain,
                                 String authType) throws CertificateException {
                     return true;
                 }
             }).build();
             SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext);
             return HttpClients.custom().setSSLSocketFactory(sslsf).build();
         } catch (KeyManagementException e) {
             e.printStackTrace();
         } catch (NoSuchAlgorithmException e) {
             e.printStackTrace();
         } catch (KeyStoreException e) {
             e.printStackTrace();
         }
         return  HttpClients.createDefault();
}
通過這個client訪問https的url地址
關(guān)鍵代碼:
//上面的工具類
CloseableHttpClient httpClient = HttpClientUtil.createSSLClientDefault();
HttpGet get = new HttpGet();
get.setURI(new URI("你的https://地址"));
httpClient.execute(get)
//...........后續(xù)操作

SSLContextBuilder
Android Https請求的簡單使用(Volley Https請求的示例)

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末诉字,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖拔稳,帶你破解...
    沈念sama閱讀 219,490評論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異锹雏,居然都是意外死亡巴比,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,581評論 3 395
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來轻绞,“玉大人采记,你說我怎么就攤上這事≌” “怎么了唧龄?”我有些...
    開封第一講書人閱讀 165,830評論 0 356
  • 文/不壞的土叔 我叫張陵,是天一觀的道長奸远。 經(jīng)常有香客問我既棺,道長,這世上最難降的妖魔是什么懒叛? 我笑而不...
    開封第一講書人閱讀 58,957評論 1 295
  • 正文 為了忘掉前任丸冕,我火速辦了婚禮,結(jié)果婚禮上薛窥,老公的妹妹穿的比我還像新娘胖烛。我一直安慰自己,他們只是感情好诅迷,可當我...
    茶點故事閱讀 67,974評論 6 393
  • 文/花漫 我一把揭開白布佩番。 她就那樣靜靜地躺著,像睡著了一般罢杉。 火紅的嫁衣襯著肌膚如雪趟畏。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,754評論 1 307
  • 那天屑那,我揣著相機與錄音拱镐,去河邊找鬼。 笑死持际,一個胖子當著我的面吹牛沃琅,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播蜘欲,決...
    沈念sama閱讀 40,464評論 3 420
  • 文/蒼蘭香墨 我猛地睜開眼益眉,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了姥份?” 一聲冷哼從身側(cè)響起郭脂,我...
    開封第一講書人閱讀 39,357評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎澈歉,沒想到半個月后展鸡,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,847評論 1 317
  • 正文 獨居荒郊野嶺守林人離奇死亡埃难,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,995評論 3 338
  • 正文 我和宋清朗相戀三年莹弊,在試婚紗的時候發(fā)現(xiàn)自己被綠了涤久。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 40,137評論 1 351
  • 序言:一個原本活蹦亂跳的男人離奇死亡忍弛,死狀恐怖响迂,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情细疚,我是刑警寧澤蔗彤,帶...
    沈念sama閱讀 35,819評論 5 346
  • 正文 年R本政府宣布,位于F島的核電站疯兼,受9級特大地震影響然遏,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜吧彪,卻給世界環(huán)境...
    茶點故事閱讀 41,482評論 3 331
  • 文/蒙蒙 一啦鸣、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧来氧,春花似錦、人聲如沸香拉。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,023評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽凫碌。三九已至扑毡,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間盛险,已是汗流浹背瞄摊。 一陣腳步聲響...
    開封第一講書人閱讀 33,149評論 1 272
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留苦掘,地道東北人换帜。 一個月前我還...
    沈念sama閱讀 48,409評論 3 373
  • 正文 我出身青樓,卻偏偏與公主長得像鹤啡,于是被迫代替她去往敵國和親惯驼。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 45,086評論 2 355

推薦閱讀更多精彩內(nèi)容

  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理递瑰,服務發(fā)現(xiàn)祟牲,斷路器,智...
    卡卡羅2017閱讀 134,672評論 18 139
  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 172,187評論 25 707
  • CSV 是一種非常方便的數(shù)據(jù)交換格式抖部。業(yè)務人員可以方便的在 Excel 進行編輯说贝,然后上傳到業(yè)務系統(tǒng)中。但是對于 ...
    lvjian700閱讀 33,252評論 0 13
  • 每個人都會有自己的夢想慎颗,這個夢想可大可小乡恕,可能它是一個小小的愿望言询,也許它是一個偉大的心愿。 但是所有事情都不會順著...
    踩高蹺的小孩閱讀 121評論 0 1
  • 文/泥步行 〖壞情緒〗 發(fā)怒是一匹自以為是的惡狼 它會吞噬你所有的理智 賦予你所有的壞情緒 它會讓你喪失所有的意志...
    花非物欲閱讀 299評論 0 1