Http session synchronization between webview and j

2019-04-15 07:49发布

问题:

I am developing hybrid application by using webview and native both. I am using ajax post method in my webview and also using post method via HttpClient on my default android code. But even if i go to same server my session id's doesn't match with each other.

Is there any way to make http request within same session in my application? Thanks for any advice.

回答1:

I have solved this issue:

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();
}