天天看點

關于雙向認證,使用HttpsURLConnection通路Https安全連結

一、 概述

最近在Android開發群裡聽小夥伴們問道了一個關于OkHttp加了證書能通路到Https的url,但是通路不到Http的url,對此,當時想到的是執行個體化兩個OkHttp的對象,一個加證書通路,另一個不加證書去通路,自己也沒有實踐,也隻是憑空想象,不知道你們是不是也是這樣想的呢?言歸正傳,今天就能講講自己用HttpsUrlConnection來通路證書連結。
           

二、核心代碼

精簡一下代碼:
這裡我寫了一個工具類,ParseUtils。

  -  解析json
  -  解析圖檔
  -  解析xml
           
public class ParseUtils {
    public final static String HOST = "cil.vicenter";

    /**
     *  解析公用方法(含有驗證證書部分)
     * @param ctx
     * @param result
     * @param url
     * @return
     * @throws IOException
     * @throws NoSuchAlgorithmException
     * @throws KeyManagementException
     */
    public static String ParseResult(Context ctx,String result, URL url)
            throws IOException, NoSuchAlgorithmException,
            KeyManagementException {
        HttpsURLConnection conn;
        conn = (HttpsURLConnection) url.openConnection();
        conn.setSSLSocketFactory(HttpUrlConnSSLSocketFactory
                .getSSLSocketFactory(ctx));
        conn.setConnectTimeout( * );
        conn.setReadTimeout( * );
        conn.setHostnameVerifier(new AllowAllHostnameVerifier());
        conn.addRequestProperty("Accept-Language", Locale.getDefault().toString());
        conn.addRequestProperty("Host", HOST);
        conn.addRequestProperty("Connection", "Keep-Alive");
        conn.addRequestProperty("X-Requested-With", "XMLHttpRequest");
        conn.addRequestProperty("loginType", "mobile");
        conn.connect();
        if (conn.getResponseCode() == ) {
            InputStreamReader isr = new InputStreamReader(
                    conn.getInputStream());
            BufferedReader bufferReader = new BufferedReader(isr);
            String inputLine = "";
            while ((inputLine = bufferReader.readLine()) != null) {
                result += inputLine + "\n";
            }
        }
        Log.e(ctx.getClass().getSimpleName(), result);
        return result;
    }


    /**
     *  解析圖檔方法(含有驗證證書部分)
     * @param ctx
     * @param result
     * @param url
     * @return
     * @throws IOException
     * @throws NoSuchAlgorithmException
     * @throws KeyManagementException
     */
    public static Bitmap ParsePicResult(Context ctx, URL url)
            throws IOException, NoSuchAlgorithmException,
            KeyManagementException {
        Bitmap bitmap;
        HttpsURLConnection conn;
        conn = (HttpsURLConnection) url.openConnection();
        conn.setSSLSocketFactory(HttpUrlConnSSLSocketFactory
                .getSSLSocketFactory(ctx));
        conn.setConnectTimeout();
        conn.setHostnameVerifier(new AllowAllHostnameVerifier());
        conn.addRequestProperty("Accept-Language", Locale.getDefault().toString());
        conn.addRequestProperty("Host", HOST);
        conn.addRequestProperty("Connection", "Keep-Alive");
        conn.addRequestProperty("X-Requested-With", "XMLHttpRequest");
        conn.addRequestProperty("loginType", "mobile");
        conn.connect();
        if (conn.getResponseCode() == ) {
          InputStream is = conn.getInputStream();  
          // Get bitmap through image path  
            BitmapFactory.Options newOpts = new BitmapFactory.Options();  
            newOpts.inJustDecodeBounds = false;  //對圖像不進行真正的解碼
            newOpts.inPurgeable = true;  
            newOpts.inInputShareable = true;  
            // Do not compress  
            newOpts.inSampleSize = ;  
            newOpts.inPreferredConfig = Config.RGB_565;  
          bitmap = BitmapFactory.decodeStream(is,null, newOpts);  
          is.close();  
          return bitmap;
        }
        return null;
    }


    /**
     *  解析公用方法(含有驗證證書部分)
     * @param ctx
     * @param result
     * @param url
     * @return
     * @throws IOException
     * @throws NoSuchAlgorithmException
     * @throws KeyManagementException
     */
    public static InputStream ParseXmlResult(Context ctx,String result, URL url,float outWidth, float outHeight)
            throws IOException, NoSuchAlgorithmException,
            KeyManagementException {
        HttpsURLConnection conn;
        conn = (HttpsURLConnection) url.openConnection();
        conn.setSSLSocketFactory(HttpUrlConnSSLSocketFactory
                .getSSLSocketFactory(ctx));
        conn.setConnectTimeout( * );
        conn.setReadTimeout( * );
        conn.setHostnameVerifier(new AllowAllHostnameVerifier());
        conn.addRequestProperty("Accept-Language", Locale.getDefault().toString());
        conn.addRequestProperty("Host", HOST);
        conn.addRequestProperty("Connection", "Keep-Alive");
        conn.addRequestProperty("X-Requested-With", "XMLHttpRequest");
        conn.addRequestProperty("loginType", "mobile");
        conn.connect();
        InputStream is = conn.getInputStream();
        return is;
    }
           

 三、實作

這裡實作很簡單,我用的是AsyncTask異步加載

加載json資料

private void runHttpsRequestWithHttpsURLConnection() {
AsyncTask<String, Void, String> testTask = new AsyncTask<String, Void, String>() {
@Override
protected String doInBackground(String... params) {
String result = "";
HttpsURLConnection conn = null;
try {
  URI suspectListUri = ParamUtls.getSuspectListUri(
  BaseActivity.BaseHost,BaseActivity.BasePort);
  URL url = new URL(suspectListUri.toString());
  result = ParseUtils.ParseResult(mContext, result, url);
  return result;
} catch (Exception e) {
    e.printStackTrace();
} 
return null;
}

@Override
protected void onPostExecute(String result) {
    super.onPostExecute(result);
}};
testTask.execute();
}

  加載圖檔部分
 String suspetPicUri = ParamUtls.getSuspetPicUri(
  BaseActivity.BaseHost, port, checkInfo,
  ParamUtls.SMALL_ICON_TYPE_POSTFIX);

ImageLoader.getInstance().displayImage(suspetPicUri, holder.ivImg, OptionsUtils.getHeadOptions());

 加載xml似乎沒用到但是絕對也能用的

           

 四、源碼部分

看了整個實作是不是很簡單呢

由于部落客寫部落格資曆太淺,上傳不了源碼,需要的可以留言給我,留下自己的郵箱也可以。

繼續閱讀