android 使用xutils3 https详解

随着17年ios上线必须要支持https,以及考虑到网络安全这块,越来越多的APP开发支持和使用https。

在gradle里配置
compile 'org.xutils:xutils:3.2.2'

在Application里配置

  x.Ext.init(this);
  x.Ext.setDebug(BuildConfig.DEBUG);

编写NetWorkUtils.java文件

public class NetWorkUtils {

    private static SSLContext mSSLContext = null;
    private static final String TAG = "NetWorkUtils";
    public static int DEFAULT_CACHE_EXPIRY_TIME = 30 * 1000;

    /**
     * http get请求
     *
     * @param params   请求参数 get请求使用 addQueryStringParameter方法添加参数
     * @param callback 回调对象
     */
    public static Callback.Cancelable getHttpRequest(RequestParams params, final HttpCallback callback) {
        return sendHttpRequest(HttpMethod.GET, params, callback);
    }

    /**
     * http post请求
     *
     * @param params   请求参数 post请求使用 addBodyParameter方法添加参数
     * @param callback 回调对象
     */
    public static Callback.Cancelable postHttpRequest(RequestParams params, final HttpCallback callback) {
        return sendHttpRequest(HttpMethod.POST, params, callback);
    }


    public static Callback.Cancelable sendHttpRequest(HttpMethod method, RequestParams params, final HttpCallback callback) {

        if (params == null) {
            params = new RequestParams();
        }

        params.setCacheMaxAge(1000 * 0); //为请求添加缓存时间
        params.setConnectTimeout(DEFAULT_CACHE_EXPIRY_TIME);
        final String url = params.getUri();

        LogUtil.d("sendRequest: url = " + url);
        SSLContext sslContext = getSSLContext(GoPlusApplication.getApplication());
        if (null == sslContext) {
            if (BuildConfig.DEBUG) LogManager.d(TAG, "Error:Can't Get SSLContext!");
            return null;
        }

        params.setSslSocketFactory(sslContext.getSocketFactory());

        return x.http().request(method, params, new Callback.CommonCallback() {

            @Override
            public void onCancelled(CancelledException msg) {
                Toast.makeText(text, msg.getMessage(), Toast.LENGTH_SHORT).show();
                callback.onFinished();
            }

            @Override
            public void onError(Throwable arg0, boolean arg1) {
                Toast.makeText(text, arg0.getMessage(), Toast.LENGTH_SHORT).show();
                LogManager.i(TAG, "==> RequestCallBack.onError()");
                LogManager.e(TAG, "==> response:" + arg0.getMessage() + "\n==> error:" + arg1);
                callback.onFinished();
            }

            @Override
            public void onSuccess(String result) {
                LogManager.i(TAG, "==> RequestCallBack.onSuccess()");
                if (result == null) {
                    return;
                }
                callback.onSuccess(result);
            }

            @Override
            public void onFinished() {
                LogUtil.d("onFinished");
            }
        });
    }

    /**
     * 获取Https的证书
     *
     * @param context 上下文
     * @return SSL的上下文对象
     */
    private static SSLContext getSSLContext(Context context) {
        CertificateFactory certificateFactory = null;
        InputStream inputStream = null;
        Certificate cer = null;
        KeyStore keystore = null;
        TrustManagerFactory trustManagerFactory = null;
        try {
            certificateFactory = CertificateFactory.getInstance("X.509");
            inputStream = context.getAssets().open("baidu.cer");//这里导入SSL证书文件
            try {
                cer = certificateFactory.generateCertificate(inputStream);
                LogManager.i(TAG, cer.getPublicKey().toString());
            } finally {
                inputStream.close();
            }

            //创建一个证书库,并将证书导入证书库
            keystore = KeyStore.getInstance(KeyStore.getDefaultType());
            keystore.load(null, null); //双向验证时使用
            keystore.setCertificateEntry("trust", cer);

            // 实例化信任库
            trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
            trustManagerFactory.init(keystore);

            mSSLContext = SSLContext.getInstance("TLS");
            mSSLContext.init(null, trustManagerFactory.getTrustManagers(), new SecureRandom());

            //信任所有证书 (官方不推荐使用)
//         s_sSLContext.init(null, new TrustManager[]{new X509TrustManager() {
//
//              @Override
//              public X509Certificate[] getAcceptedIssuers() {
//                  return null;
//              }
//
//              @Override
//              public void checkServerTrusted(X509Certificate[] arg0, String arg1)
//                      throws CertificateException {
//
//              }
//
//              @Override
//              public void checkClientTrusted(X509Certificate[] arg0, String arg1)
//                      throws CertificateException {
//
//              }
//          }}, new SecureRandom());

            return mSSLContext;

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}

  public static abstract class HttpCallback {
        public abstract void onSucc(String result);

        public abstract void onfailed();
    }

在activity中调用

RequestParams params = new RequestParams(url);
  NetWorkUtils.postHttpRequest(params, new HttpCallback() {
            @Override
            public void onSuccess(String result) {
            }

            @Override
            public void onFinished() {
            }
        });

    }

你可能感兴趣的:(android)