Android中的webview和java http客户端之间的Http会话同步

时间:2012-03-20 22:24:29

标签: android http httpclient android-webview httprequest

我正在使用webview和native来开发混合应用程序。我在我的webview中使用ajax post方法,并在我的默认android代码上通过HttpClient使用post方法。 但即使我去同一台服务器,我的会话ID也不会相互匹配。

有没有办法在我的应用程序中的同一会话中发出http请求? 谢谢你的任何建议。

1 个答案:

答案 0 :(得分:4)

我已经解决了这个问题:

public void syncSession(final Context ctx){

    new Thread(new Runnable(){
        public void run(){

            //Products will be stated in memory 
            ProductManager pm = ProductManager.getInstance();

            //              HttpClient httpclient = new DefaultHttpClient();
            HttpPost httpget = new HttpPost(UrlConstants.SERVICE_URL_SYNC);
            HttpResponse response;
            String result = null;
            try {
                response = httpclient.execute(httpget);
                //write db to 

            } catch (ClientProtocolException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } 



            List<Cookie> cookies = httpclient.getCookieStore().getCookies();

            if (! cookies.isEmpty()){

                CookieSyncManager.createInstance(ctx);
                CookieManager cookieManager = CookieManager.getInstance();

                //sync all the cookies in the httpclient with the webview by generating cookie string
                for (Cookie cookie : cookies){

                    Cookie sessionInfo = cookie;

                    String cookieString = sessionInfo.getName() + "=" + sessionInfo.getValue() + "; domain=" + sessionInfo.getDomain();
                    cookieManager.setCookie(UrlConstants.SERVICE_PRE_URL, cookieString);
                    CookieSyncManager.getInstance().sync();
                }
            }

        }
    }).start();
}