Android HTTPS和Cookie,API级别8

时间:2012-10-26 14:07:00

标签: java android session cookies https

我正在编写一个必须通过HTTPS连接到服务器的Android应用程序。我试过的第一个解决方案就是这个: (不要介意安全漏洞)

final static HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier() {
    public boolean verify(String hostname, SSLSession session) {
        return true;
    }
};
private static void trustAllHosts() {
    // Create a trust manager that does not validate certificate chains
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return new java.security.cert.X509Certificate[] {};
        }

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

        public void checkServerTrusted(X509Certificate[] chain,
                String authType) throws CertificateException {
        }
    } };

    // Install the all-trusting trust manager
    try {
        SSLContext sc = SSLContext.getInstance("TLS");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
             HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    } catch (Exception e) {
        Log.d("USR_SSL", e.getMessage());
    }
}
//...

@Override
protected String doInBackground(String... params) {
    try {

        URL url = new URL(params[0]);
                    //This is an HTTPS url
        String jsonStr = "";
        if(params.length > 1) {
            jsonStr = params[1];
        }
        HttpsURLConnection urlConn = (HttpsURLConnection) url.openConnection();
        trustAllHosts();
        urlConn.setHostnameVerifier(DO_NOT_VERIFY);
        urlConn.setRequestProperty("Content-Type", "application/json");
        urlConn.setRequestProperty("Accept", "application/json");
        urlConn.setRequestMethod("POST");

        OutputStream os = urlConn.getOutputStream();
        os.write(jsonStr.getBytes());
        os.flush();
//...

一切都很好和花花公子(差不多),直到我意识到我还必须使用身份验证,会话和所有好东西。它应该是非常好的使用:

CookieManager cookieManager = new CookieManager();  
CookieHandler.setDefault(cookieManager);

但不幸的是我们必须支持Android API级别8,这意味着上面两行代码将无效。鉴于此,我已经在互联网上搜索了几个小时,尝试使用Apache类构建解决方案,这似乎支持HTTPS和Cookie。

这是我设法缝合在一起的代码:

public class ConnectionMediator {
public class MySSLSocketFactory extends SSLSocketFactory {
    SSLContext sslContext = SSLContext.getInstance("TLS");

    public MySSLSocketFactory(KeyStore truststore) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {
        super(truststore);

        TrustManager tm = new X509TrustManager() {
            public void checkClientTrusted(X509Certificate[] chain, String authType) {
            }

            public void checkServerTrusted(X509Certificate[] chain, String authType) {
            }

            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        };
        sslContext.init(null, new TrustManager[] { tm }, null);
    }

    @Override
    public Socket createSocket(Socket socket, String host, int port, boolean autoClose) throws IOException, UnknownHostException {
        return sslContext.getSocketFactory().createSocket(socket, host, port, autoClose);
    }

    @Override
    public Socket createSocket() throws IOException {
        return sslContext.getSocketFactory().createSocket();
    }
}
public void tryConnect(String url, String data) {
    try {
        //SSL Stuff
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);

        SSLSocketFactory sf = new MySSLSocketFactory(trustStore);
        sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

        HttpParams params = new BasicHttpParams();
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);

        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        registry.register(new Scheme("https", sf, 443));

        ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);

        DefaultHttpClient httpClient = new  DefaultHttpClient(ccm, params);

        //Cookie stuff
        HttpContext localContext = new BasicHttpContext();
        HttpResponse response = null;
        HttpPost httpPost = null;
        StringEntity tmp = null;

        httpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.RFC_2109);
        httpPost = new HttpPost(url);

        tmp = new StringEntity(data,"UTF-8");
        httpPost.setEntity(tmp);

        response = httpClient.execute(httpPost,localContext);
    } catch(Exception e) {
        Log.d("USR_DEBUG", e.getClass().toString() + ": " + e.getMessage());
    }

}
}

在撰写本文时,我得到NetworkOnMainThreadException,但这并不重要;重要的是,我希望指出的是我不知道我在做什么,就像在,通过HTTPS连接并使用cookie一样,必须使用13种不同的我从未听说过的课程。显然,我对HTTPS / Java网络类的了解接近于零,但尽管如此,我还是期望更直观的东西。因此,不是“这不起作用”的问题,我的问题是“我应该做什么”,甚至“如何了解我必须做什么?”。

非常感谢,

一个非常困惑的编码器

1 个答案:

答案 0 :(得分:2)

我的初步问题包括两部分:第一部分,如何使用HTTPS;第二部分,如何同时使用Cookie。

我的问题还不够彻底,因为我已经部分回答了 - 我最初发布的代码与HTTPS有关,而NetworkOnMainThreadException发生了因为我没有单独运行代码线程,例如,使用AsyncTask

但是,为了正确使用cookie,人们应该使用类似于以下的解决方案:

public class State {
    private static HttpContext httpContext;
    public static HttpContext getHttpContext() {
        if(httpContext == null) {
            httpContext = new BasicHttpContext();
            CookieStore cookieStore = getCookieStore();
            httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
        }
        return httpContext;
    }
    private static CookieStore cookieStore;
    public static CookieStore getCookieStore() {
        if(cookieStore == null) {
            cookieStore = new BasicCookieStore();
        }
        return cookieStore;
    }
}

我不确定这是否是“Android”方式(使用静态类)但它有效:

    //...
    //Connection objects
    DefaultHttpClient httpClient = new DefaultHttpClient(ccm, params);
    HttpPost httpPost = null;

    //Cookie stuff
    HttpContext httpContext = State.getHttpContext();
    httpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.RFC_2109);
    //....

如果使用相同的HttpClientCookieStore,则每次保留会话时似乎使用其他HttpContext。 虽然这个答案使“事情有效”(这就是我现在所需要的),但它并不是一个彻底的答案,因为它根本无法解释为什么需要超过10个类来将所有内容连接在一起。