ANDROID : Share session between Webview and httpclient

后端 未结 2 1912
失恋的感觉
失恋的感觉 2020-12-02 12:53

I have actually a logged session in my WebView. But I use also httpclient to send and get data from the web. I saw on the internet that it\'s impossible to get the content o

相关标签:
2条回答
  • 2020-12-02 13:16

    Follow this tuto :

    http://metatroid.com/article/Android:%20handling%20web%20service%20authentication

    =============================== Here the content of the webpage =====

    Something you might find yourself doing in Android is web authentication. Most web sites issue a cookie to track session ID's and keep a user logged in. In order to maintain this authentication, you will need to keep cookies synced between activities and between http clients and webviews.

    The method I ended up doing, which seems to work well enough, was to create a class that extends Application, then define a single HttpClient to be used throughout the rest of the Application. That code looks like:

    public class AppSettings extends Application {
        private static final DefaultHttpClient client = createClient();
    
        @Override
        public void onCreate(){
        }
    
        static DefaultHttpClient getClient(){
                return client;
        }
        private static DefaultHttpClient createClient(){
                BasicHttpParams params = new BasicHttpParams();
                SchemeRegistry schemeRegistry = new SchemeRegistry();
                schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
                final SSLSocketFactory sslSocketFactory = SSLSocketFactory.getSocketFactory();
                schemeRegistry.register(new Scheme("https", sslSocketFactory, 443));
                ClientConnectionManager cm = new ThreadSafeClientConnManager(params, schemeRegistry);
                DefaultHttpClient httpclient = new DefaultHttpClient(cm, params);
                httpclient.getCookieStore().getCookies();
                return httpclient;
        }
    

    This class also creates an HttpClient that is suitable for AsyncTasks and making multiple simultaneous http requests. Using ThreadSafeClientConnManager for the ClientConnectionManager let's you run http requests inside AsyncTasks without causing a force close when you press the back button and start a second, or third.

    It also creates a single default cookie store that can be accessed in all your activities. You would use this in your other activities by calling the getClient() method.

    For example

    public class SomeActivity extends Activity {
            static DefaultHttpClient mClient = AppSettings.getClient();
            ...
            try {
    
                HttpGet httpget = new HttpGet('URL');
                HttpResponse response;
                response = mClient.execute(httpget);
                ...
            }
            ...
        }
    

    If you find it necessary to use a webview and need it to access and use the same cookies as your client. You can sync the client's cookie store using CookieManager: (in onPageStarted method)

    DefaultHttpClient mClient = AppSettings.getClient();
    
    
    Cookie sessionInfo;
    List<Cookie> cookies = mClient.getCookieStore().getCookies();
    
    if (! cookies.isEmpty()){
            CookieSyncManager.createInstance(getApplicationContext());
            CookieManager cookieManager = CookieManager.getInstance();
    
            for(Cookie cookie : cookies){
                    sessionInfo = cookie;
                    String cookieString = sessionInfo.getName() + "=" + sessionInfo.getValue() + "; domain=" + sessionInfo.getDomain();
                    cookieManager.setCookie("example.com", cookieString);
                    CookieSyncManager.getInstance().sync();
            }
    }
    

    You will need to switch example.com with the correct domain.

    0 讨论(0)
  • 2020-12-02 13:19

    So , this is what I did and it worked for me -

    HttpRequestBase request = new HttpGet(uri);
    request.addHeader("Cookie", getCookieFromAppCookieManager(uri.toString()));
    

    Now the implmentation for the getCookieFromAppCookieManager is as follows -
    The method gets the cookies for a given URL from the application CookieManager. The application CookieManager manages the cookies used by an application's WebView instances.

    @param url the URL for which the cookies are requested
    @return value the cookies as a string, using the format of the 'Cookie' HTTP request header
    @throws MalformedURLException
    
    
    public static String getCookieFromAppCookieManager(String url) throws MalformedURLException {
        CookieManager cookieManager = CookieManager.getInstance();
        if (cookieManager == null)
            return null;
        String rawCookieHeader = null;
        URL parsedURL = new URL(url);
    
        // Extract Set-Cookie header value from Android app CookieManager for this URL
        rawCookieHeader = cookieManager.getCookie(parsedURL.getHost());
        if (rawCookieHeader == null)
            return null;
        return rawCookieHeader;
    }
    
    0 讨论(0)
提交回复
热议问题