Android开发框架xUtils3.x新手教学(二)HTTPS访问

现在越来越多的项目采用Https安全通信,今天来介绍一下xUtils里如何使用Https。

一、弄一个SSL证书(.crt文件),放到项目assets目录下。

二、建立HttpUtils类,代码如下:

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;

/**
 * HttpUtil
 * 项目名称: 
 * 包:      
 * 类名称:    HttpUtil
 * 类描述:    Http请求工具类
 * 创建人:    XuJiayin
 * 创建时间:  2016-03-16
 * 修改人:    XuJiayin
 * 修改时间:  2016-03-16
 * 修改备注:  Http请求工具类
 * 版本:      v1.0
 */

public class HttpUtil {
    /** Https 证书验证对象 */
    private static SSLContext s_sSLContext = null;

    /**
     * Https请求发送
     * @param context Activity(fragment)的资源上下文
     * @param params 发送的请求
     * @param callBack 回调对象(具体接口形式参见xUtils sample的httpFragment.java)
     * @return true=正常调用 false=异常调用
     */
    public static boolean send(Context context, RequestParams params, Callback.CommonCallback callBack) {
        /* 判断https证书是否成功验证 */
        SSLContext sslContext = getSSLContext(context);
        if(null == sslContext){
            if (BuildConfig.DEBUG) Log.d("HttpUtil", "Error:Can't Get SSLContext!");
            return false;
        }
        //绑定SSL证书
        params.setSslSocketFactory(sslContext.getSocketFactory());
        x.http().request(HttpMethod.POST, params, callBack);
        return true;
    }

    /**
     * Https下载图片
     * @param context Activity(fragment)的资源上下文
     * @return InputStream
     */
    public static InputStream getRequestInputstream(Context context, String path) throws Exception {
        /* 判断https证书是否成功验证 */
        SSLContext sslContext = getSSLContext(context);
        if(null == sslContext){
            if (BuildConfig.DEBUG) Log.d("HttpUtil", "Error:Can't Get SSLContext!");
            return null;
        }
        //绑定SSL证书
        java.net.URL url = new java.net.URL(path);
        HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
        conn.setSSLSocketFactory(sslContext.getSocketFactory());
        conn.setRequestMethod("POST");
        conn.setDoOutput(true);
        conn.setDoInput(true);
        //连接
        conn.connect();
        return conn.getInputStream();
    }

    /**
     * Https请求发送(同步请求 上传图片使用)
     * @param context Activity(fragment)的资源上下文
     * @param params 发送的请求
     * @param callBack 回调对象(具体接口形式参见xUtils sample的httpFragment.java)
     * @return true=正常调用 false=异常调用
     */
    public static boolean sendSync(Context context, RequestParams params, Callback.TypedCallback callBack) throws Throwable {
        /* 判断https证书是否成功验证 */
        SSLContext sslContext = getSSLContext(context);
        if(null == sslContext){
            if (BuildConfig.DEBUG) Log.d("HttpUtil", "Error:Can't Get SSLContext!");
            return false;
        }
        //绑定SSL证书
        params.setSslSocketFactory(sslContext.getSocketFactory());
        x.http().requestSync(HttpMethod.POST, params, callBack);
        return true;
    }

    /**
     * 获取Https的证书
     * @param context Activity(fragment)的上下文
     * @return SSL的上下文对象
     */
    private static SSLContext getSSLContext(Context context) {
        if (null != s_sSLContext) {
            return s_sSLContext;
        }

        //以下代码来自百度 参见http://www.tuicool.com/articles/vmUZf2
        CertificateFactory certificateFactory = null;

        InputStream inputStream = null;
        KeyStore keystore = null;
        String tmfAlgorithm = null;
        TrustManagerFactory trustManagerFactory = null;
        try {
            certificateFactory = CertificateFactory.getInstance("X.509");

            inputStream = context.getAssets().open("leichi.crt");//这里导入SSL证书文件
//            inputStream = context.getAssets().open("51p2b_server_bs.pem");//这里导入SSL证书文件

            Certificate ca = certificateFactory.generateCertificate(inputStream);

            keystore = KeyStore.getInstance(KeyStore.getDefaultType());
            keystore.load(null, null);
            keystore.setCertificateEntry("ca", ca);

            tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
            trustManagerFactory = TrustManagerFactory.getInstance(tmfAlgorithm);
            trustManagerFactory.init(keystore);

            // Create an SSLContext that uses our TrustManager
            s_sSLContext = SSLContext.getInstance("TLS");
            s_sSLContext.init(null, trustManagerFactory.getTrustManagers(), null);
            return s_sSLContext;
        } catch (CertificateException e) {
            e.printStackTrace();
        } catch (KeyManagementException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (KeyStoreException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

   
}

三、如何使用?

//声明:网路请求参数
RequestParams params = new RequestParams(URL);
params.addBodyParameter("param", "Hello xUtils!");    // 添加参数
/** 发送登录请求 */
HttpUtil.send(content, params, new Callback.CommonCallback() {//回调函数内容});
这里我们使用了GSON来序列化JSON字符串,如果没这个需要的同学,直接调用 addBodyParameter添加要传的参数即可。

使用GSON不在本教程之内,请大家自行查阅。

 
  

你可能感兴趣的:(Android,Android,xUtils,HTTPS)