码迷,mamicode.com
首页 > Web开发 > 详细

Google Volley框架之https请求

时间:2015-06-09 11:48:58      阅读:136      评论:0      收藏:0      [点我收藏+]

标签:

先插一句,Google出的volley框架本身是支持https请求的,但是只是针对有第三方机构认证过的。

如果自己随便在网上搞的一个证书,那volley是不支持请求的。


本文讲下如何让volley支持自己搞的https证书。


修改volley源码:com.android.myvolley.toolbox.HurlStack

   /**
     * Create an {@link HttpURLConnection} for the specified {@code url}.
     */
    protected HttpURLConnection createConnection(URL url) throws IOException {
        if (url.toString().contains("https")) {
            MyHttpsManager.allowAllSSL();
        }
        return (HttpURLConnection) url.openConnection();
    }
在HurlStack类中的createConnection方法中,做个过滤处理:

if (url.toString().contains("https")) {
            MyHttpsManager.allowAllSSL();
        }
直接贴代码啦。

import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

public class MyHttpsManager implements X509TrustManager {
    private static TrustManager[] trustManagers;

    @Override
    public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {

    }

    @Override
    public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {

    }

    @Override
    public X509Certificate[] getAcceptedIssuers() {
        return new X509Certificate[0];
    }

    public static void allowAllSSL() {
        HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {

            @Override
            public boolean verify(String arg0, SSLSession arg1) {
                // TODO Auto-generated method stub
                return true;
            }

        });

        SSLContext context = null;
        if (trustManagers == null) {
            trustManagers = new TrustManager[] { new MyHttpsManager() };
        }

        try {
            context = SSLContext.getInstance("TLS");
            context.init(null, trustManagers, new SecureRandom());
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (KeyManagementException e) {
            e.printStackTrace();
        }

        HttpsURLConnection.setDefaultSSLSocketFactory(context
                .getSocketFactory());
    }
}

然后请求的时候在头里面加个什么鬼id,sign之类的,就可以和服务端通信了。

例如volley重写getHeaders方法:

public void sendRequest(int method, String url, JSONObject jsonRequest, final String sessionToken, final OnResponseListener listener,final OnErrorListener errorListener) {
        initUserAgent();

        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(method, url, jsonRequest, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                listener.onResponse(response);
            }

        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                errorListener.onErrorResponse(error);
            }
        }){
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                HashMap<String, String> headers = new HashMap<String,String>();
                headers.put("Content-Type", "application/json");
                headers.put("x-app-id", APPID);
                headers.put("x-app-sign",SIGN);
                headers.put("x-session-token",sessionToken);
                headers.put("User-Agent",userAgent);
                return headers;
            }
        };

        Volley.newRequestQueue(context).add(jsonObjectRequest);
    }


Google Volley框架之https请求

标签:

原文地址:http://blog.csdn.net/y_chengyong/article/details/46424343

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!