Anroid https代码示例

本网站用的阿里云ECS,推荐大家用。自己搞个学习研究也不错

https与http的通信,在我看来主要的区别在于https多了一个安全验证机制,而Android采用的是X509验证,首先我们需要这重写X509类,建立我们的验证规则、、不过对于特定的项目,我们一般都是无条件信任服务端的,因此我们可以对任何证书都无条件信任(其实本质上我们只是信任了特定url的证书,为了偷懒,才那么选择的)/**

 * 信任所有主机-对于任何证书都不做检查
 */
class MytmArray implements X509TrustManager {
    public X509Certificate[] getAcceptedIssuers() {
        // return null;
        return new X509Certificate[] {};
    }
    @Override
    public void checkClientTrusted(X509Certificate[] chain, String authType)
            throws CertificateException {
        // TODO Auto-generated method stub
    }
    @Override
    public void checkServerTrusted(X509Certificate[] chain, String authType)
            throws CertificateException {
        // TODO Auto-generated method stub
        // System.out.println("cert: " + chain[0].toString() + ", authType: "
        // + authType);
    }
};

好了,我们写好了信任规则,接下载就要创建一个主机的信任列表

static TrustManager[] xtmArray = new MytmArray[] { new MytmArray() };
    /**
     * 信任所有主机-对于任何证书都不做检查
     */
    private static void trustAllHosts() {
        // Create a trust manager that does not validate certificate chains
        // Android 采用X509的证书信息机制
        // Install the all-trusting trust manager
        try {
            SSLContext sc = SSLContext.getInstance("TLS");
            sc.init(null, xtmArray, new java.security.SecureRandom());
            HttpsURLConnection
                    .setDefaultSSLSocketFactory(sc.getSocketFactory());
            // HttpsURLConnection.setDefaultHostnameVerifier(DO_NOT_VERIFY);//
            // 不进行主机名确认
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    static HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier() {
        @Override
        public boolean verify(String hostname, SSLSession session) {
            // TODO Auto-generated method stub
            // System.out.println("Warning: URL Host: " + hostname + " vs. "
            // + session.getPeerHost());
            return true;
        }
    };

上面的都是https通信需要做的几个基本要求,接下载我们要做的就是https的使用啦下面就以get和post为例进行说明,中间还涉及到cookie的使用

String httpUrl="XXXXX"
String result = "";
        HttpURLConnection http = null;
        URL url;
        try {
            url = new URL(httpUrl);
            // 判断是http请求还是https请求
            if (url.getProtocol().toLowerCase().equals("https")) {
                trustAllHosts();
                http = (HttpsURLConnection) url.openConnection();
                ((HttpsURLConnection) http).setHostnameVerifier(DO_NOT_VERIFY);// 不进行主机名确认
            } else {
                http = (HttpURLConnection) url.openConnection();
            }
            http.setConnectTimeout(10000);// 设置超时时间
            http.setReadTimeout(50000);
            http.setRequestMethod("GET");// 设置请求类型为
            http.setDoInput(true);
            http.setRequestProperty("Content-Type", "text/xml");
//http.getResponseCode());http或https返回状态200还是403
BufferedReader in = null;
            if (obj.getHttpStatus() == 200) {
                getCookie(http);
                in = new BufferedReader(new InputStreamReader(
                        http.getInputStream()));
            } else
                in = new BufferedReader(new InputStreamReader(
                        http.getErrorStream()));
            result = in.readLine();
            Log.i("result", result);
            in.close();
            http.disconnect();
 https或http的get请求写好了,哦中间涉及到了一个getCookie的方法,如下:
Java代码  收藏代码
/** 得到cookie */
    private static void getCookie(HttpURLConnection http) {
        String cookieVal = null;
        String key = null;
        DataDefine.mCookieStore = "";
        for (int i = 1; (key = http.getHeaderFieldKey(i)) != null; i++) {
            if (key.equalsIgnoreCase("set-cookie")) {
                cookieVal = http.getHeaderField(i);
                cookieVal = cookieVal.substring(0, cookieVal.indexOf(";"));
                DataDefine.mCookieStore = DataDefine.mCookieStore + cookieVal
                        + ";";
            }
        }
    }
public static Query HttpQueryReturnClass(String httpUrl, String base64) {

Java代码  收藏代码
        String result = "";
        Log.i("控制", httpUrl);
        Query obj = new Query();
        HttpURLConnection http = null;
        URL url;
        try {
            url = new URL(httpUrl);
            // 判断是http请求还是https请求
            if (url.getProtocol().toLowerCase().equals("https")) {
                trustAllHosts();
                http = (HttpsURLConnection) url.openConnection();
                ((HttpsURLConnection) http).setHostnameVerifier(DO_NOT_VERIFY);// 不进行主机名确认
            } else {
                http = (HttpURLConnection) url.openConnection();
            }
            http.setConnectTimeout(10000);// 设置超时时间
            http.setReadTimeout(50000);
            http.setRequestMethod("POST");// 设置请求类型为post
            http.setDoInput(true);
            http.setDoOutput(true);
            http.setRequestProperty("Content-Type", "text/xml");
            http.setRequestProperty("Cookie", DataDefine.mCookieStore);
            DataOutputStream out = new DataOutputStream(http.getOutputStream());
            out.writeBytes(base64);
            out.flush();
            out.close();
            obj.setHttpStatus(http.getResponseCode());// 设置http返回状态200还是403
            BufferedReader in = null;
            if (obj.getHttpStatus() == 200) {
                getCookie(http);
                in = new BufferedReader(new InputStreamReader(
                        http.getInputStream()));
            } else
                in = new BufferedReader(new InputStreamReader(
                        http.getErrorStream()));
            result = in.readLine();// 得到返回结果
            in.close();
            http.disconnect();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
}

这里面的base64是我经过base64加密过以后的数据

未经允许不得转载:演道网 » Anroid https代码示例

赞 (0)
分享到:更多 ()

评论 0

评论前必须登录!

登陆 注册