关于双向认证,使用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(5 * 1000);

conn.setReadTimeout(10 * 1000);

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() == 200) {

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(30000);

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() == 200) {

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 = 4;

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(5 * 1000);

conn.setReadTimeout(10 * 1000);

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异步加载

1. 加载json数据

private void runHttpsRequestWithHttpsURLConnection() {

AsyncTask testTask = new AsyncTask() {

@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();

}

2. 加载图片部分

String suspetPicUri = ParamUtls.getSuspetPicUri(

BaseActivity.BaseHost, port, checkInfo,

ParamUtls.SMALL_ICON_TYPE_POSTFIX);

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

3. 加载xml似乎没用到但是绝对也能用的

wechat: derikli123

  • 发表于:
  • 原文链接https://kuaibao.qq.com/s/20180713G116OP00?refer=cp_1026
  • 腾讯「云+社区」是腾讯内容开放平台帐号(企鹅号)传播渠道之一,根据《腾讯内容开放平台服务协议》转载发布内容。
  • 如有侵权,请联系 yunjia_community@tencent.com 删除。

扫码关注云+社区

领取腾讯云代金券