tomcat+https協議的接口編寫及客戶端訪問

https無非就是http+ssl,也就是在http基礎上進行證書上的校驗,俗稱安全的http,其實就是配置服務器的訪問方式

具體操作步驟:

1.對服務端進行修改,接口訪問使用https

      a.利用jdk自帶的證書生成工具來生成一個key :  (生成證書等資料見後附)

keytool -genkeypair -alias certificatekey -keyalg RSA -validity 365 -keystore shfqkeystore.jks

      

                          主意一下:'您的名字與姓氏是什麼'這裏需要注意的,你所填的到時會作爲是你的域名來用

命令詳解
keytool -genkeypair -alias certificatekey -keyalg RSA -validity 365 -keystore shfqkeystore.jks
生成keystore後接着生成一個密鑰對兒。RSA是非對稱密鑰算法,也可以改爲 keytool支持的其他密鑰算法,365代表的是證書的有效期,可以自己指定,shfqkeystore.jks是keystroe的名稱,也可以自己指定。

     b.tomcat/conf/server.xml啓用ssl(把下面的這個本身是註釋掉的開啓)

      

    c.把上面tomcat配置進行修改(添加:keystoreFile="對應你生成的key文件路徑",keystorePass="你的祕鑰口令"):

     

    d.ok這樣就可以了,再來訪問下之前做的接口地址,https://localhost:8443/springMVC/user/getUserByName/cwh,結果如下,證明ssl應用成功

    

   e.至此似乎服務端接口採用https協議很成功,但是問題來了,之前http://localhost:8080/springMVC/user/getUserByName/cwh這個地址已經暴露過,別人直接通過這個訪問不也就繞過了https了麼,那麼解決辦法就是讓http訪問重定向到https去,操作如下:在tomcat目錄下的conf/web.xml此文件改位置添加如下代碼代碼:

     <security-constraint> 
      <web-resource-collection> 
      <web-resource-name>ssl</web-resource-name> 
      <url-pattern>/*</url-pattern> 
      </web-resource-collection> 
      <user-data-constraint> 
      <transport-guarantee>CONFIDENTIAL</transport-guarantee> 
      </user-data-constraint> 
    </security-constraint>

    

    ok這樣的話繼續訪問http://localhost:8080/springMVC/user/getUserByName/cwh的話會被重定向到https去:

    至此https服務端完成

2.下面進行httpclient客戶端編寫,

      在之前demo基礎上進行修改,添加證書:

     HttpClient httpclient = new DefaultHttpClient();  
      String uri = "https://localhost/springMVC/user/getUserByName/cwh"; 
            KeyStore trustStore  = KeyStore.getInstance(KeyStore.getDefaultType());
              FileInputStream instream = new FileInputStream(new File("E:/keys/cwhkey"));
              //密匙庫的密碼
              trustStore.load(instream, "caiwenhao".toCharArray());
              //註冊密匙庫
              SSLSocketFactory socketFactory = new SSLSocketFactory(trustStore);
              //不校驗域名
              socketFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
              Scheme sch = new Scheme("https", 8443, socketFactory);//8443端口
              httpclient.getConnectionManager().getSchemeRegistry().register(sch);
     注意一下:socketFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);是不校驗域名,如果註釋掉的話,那麼你訪問的uri就會報如下錯誤:
    

   這時我們需要把域名localhost改爲你的所設置的‘您的名字與姓氏是什麼’的值,https://cwh/springMVC/user/getUserByName/cwh,這裏的域名cwh是我們虛擬出來的所以我們      需要去hosts文件配置下讓cwh這個域名指向本地:打開C:\Windows\System32\drivers\etc,hosts文件添加127.0.0.1      cwh;

    還需注意的是:Scheme sch = new Scheme("https", 8443, socketFactory);設置的是我們https的端口8443

    客戶端 完整代碼如下:

      

      public void HttpPostData() {  
          try { 
              HttpClient httpclient = new DefaultHttpClient();  
              String uri = "https://localhost/springMVC/user/getUserByName/cwh"; 
              KeyStore trustStore  = KeyStore.getInstance(KeyStore.getDefaultType());
              FileInputStream instream = new FileInputStream(new File("E:/keys/cwhkey"));
              //密匙庫的密碼
              trustStore.load(instream, "caiwenhao".toCharArray());
              //註冊密匙庫
              SSLSocketFactory socketFactory = new SSLSocketFactory(trustStore);
              //不校驗域名
              socketFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
              Scheme sch = new Scheme("https", 8443, socketFactory);//8443端口
              httpclient.getConnectionManager().getSchemeRegistry().register(sch);
              HttpPost httppost = new HttpPost(uri);              
              JSONObject obj = new JSONObject();  
              HttpResponse response;  
              response = httpclient.execute(httppost);  
              //檢驗狀態碼,如果成功接收數據  
              int code = response.getStatusLine().getStatusCode();  
              System.out.println(code+"code");
              if (code == 200) {  
                  String rev = EntityUtils.toString(response.getEntity());//返回json格式: {"id": "","name": ""}         
                  obj= JSONObject.fromObject(rev);
                  System.out.println(obj.get("username"));
                  User user = (User)JSONObject.toBean(obj,User.class);
                  System.out.println("返回數據==="+user.toString());
              } 
              } catch (ClientProtocolException e) { 
                  e.printStackTrace();
              } catch (IOException e) {  
                  e.printStackTrace();
              } catch (Exception e) { 
                  e.printStackTrace();
              } 
         }
   

附:   參考地址    https://blog.csdn.net/Cy_LightBule/article/details/86680149

驗證] - jks是否可以用

keytool -list -v -keystore shfqkeystore.jks
導出證書:  keytool -export -alias certificatekey -keystore shfqkeystore.jks -rfc -file shfqcert.cer

Truststore的生成以及公鑰證書的導入

把上一步生成的公鑰證書shfqcert.cer導入到truststore中。

keytool -import -alias certificatekey -file shfqcert.cer  -keystore shfqtruststore.jks

驗證truststore文件

  • 鍵入命令
keytool -list -v -keystore shfqtruststore.jks

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章