Wednesday, March 13, 2013

https ga Java class orqali murojaat qilish

Ba'zan Java classdan https orqali biron bir urlga murojaat qilishga to'g'ri keladi. Agar o'sha serverning sertifikati to'g'i bo'lsaku muammo bo'lmaydi. Lekin sertifikatning muddati tugagan yoki o'zlari yozishgan bo'lsachi? Bu holda ancha ter to'kishga to'g'ri keladi. Chunki brauzerda sertifikatni exceptionlar ro'yhatiga qo'shib qo'yishimiz mumkin. Application serverda bunday qila olmaymiz. Shuning uchun boshqa yo'lini qidirishga to'g'ri keladi. Buni quyidagi misol yordamida ko'rib chiqamiz. Avvalgi XML haqidagi maqolada berilgan getXml() metodini https orqali ishlaydigan qilamiz.
http orqali XMLni olish:



private InputStream getXml(String url){
    InputStream res = null;
    try{    
        URL serverURL = new URL(url);
        URLConnection urlConn = (URLConnection)serverURL.openConnection();
        urlConn.setDoOutput(true);
        urlConn.setUseCaches(false);
        urlConn.setAllowUserInteraction(true);
        res = (InputStream)urlConn.getContent();
    }catch(IOException iox){
        iox.getMessage();
    }
    return res;
}

Yuqoridagi kodga e'tibor bering. URL yaratdik, URL bilan connection yaratdik va uni inputstreamga o'zlashtirib oldik. Bor yo'g'i shu. Endi shu metodning https uchun yozilgan versiyasiga e'tibor bering:
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
.........

private InputStream getXml(String url){
            //trust manager yaratamiz
            TrustManager[] trustAllCerts = new TrustManager[]{
              new X509TrustManager(){
                public java.security.cert.X509Certificate[] getAcceptedIssuers(){
                  return null;
                }
                public void checkClientTrusted(
                  java.security.cert.X509Certificate[] certs, String authType){
                }
                public void checkServerTrusted(
                  java.security.cert.X509Certificate[] certs, String authType){
                }
                public boolean isClientTrusted(
                  java.security.cert.X509Certificate[] certs){
                  return true;   
                }
                public boolean isServerTrusted(java.security.cert.X509Certificate[] certs){
                  return true;
                }
              }
            };
            //hostname verificator yaratamiz
            HostnameVerifier verifier = new HostnameVerifier(){
              public boolean verify(String string, SSLSession sSLSession){
                return true;
              }
              public boolean verify(String string, String string2){
                return true;
              }
            };
            //HttpsURLConnectionga trust manager va hostname verificator ornatamiz
            try{
                SSLContext sc = SSLContext.getInstance("SSL");
                sc.init(null, trustAllCerts, new java.security.SecureRandom());            
                HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
                HttpsURLConnection.setDefaultHostnameVerifier(verifier);            
            }catch (Exception e) {
              System.out.println("Exception "+e.getMessage());
            }
            URL serverURL = null;
            try{
                serverURL = new URL(url);
            }catch(MalformedURLException mue){
                System.out.println("MalformedURLException :"+mue.getMessage());
                mue.printStackTrace();
            }catch(ClassCastException cce){
                System.out.println("serverURL ClassCastException :"+cce.getMessage());
                cce.printStackTrace();
            }
            HttpsURLConnection urlConn = null;
            try{
              urlConn = (HttpsURLConnection)serverURL.openConnection();
            }catch(IOException ioe){
              System.out.println("IOException :"+ioe.getMessage());
              ioe.printStackTrace();
            }catch(ClassCastException cce){
                System.out.println("urlConn ClassCastException :"+cce.getMessage());
                cce.printStackTrace();
            }
            //endi qolgan qismi oson
            urlConn.setDoOutput(true);
            urlConn.setUseCaches(false);
            urlConn.setAllowUserInteraction(true);
            InputStream inputStream = null;
            try{
                inputStream = urlConn.getInputStream();            
            }catch(SocketException se){
              System.out.println("SocketException: "+se.getMessage());
              se.printStackTrace();
            }catch(IOException ioe){
              System.out.println("IOException: "+ioe.getMessage());
              ioe.printStackTrace();
            }
            return inputStream;
        }

1. Trust manager yaratamiz.
2. Host name verificator yaratamiz.
3. Trust manager va hostname verificatorlarni HttpsURLConnectionga «o'rnatamiz».
4. HttpsURLConnectiondan InputStream ga «yuklab» olamiz.
PS: Kodning import qismini batafsil yozib o'tirimadim.
Kod ishlaydi. Sinovdan o'tgan.

Manba.