How to get cookies in HttpUrlConnection by using CookieStore?

妖精的绣舞 提交于 2019-12-03 10:08:57

问题


In my Application class, I do the following:

public class MyApplication extends Application {
    private static HttpURLConnection conn = null;
    public static CookieStore cookieStore;
    public static HttpContext localContext;
    public static DefaultHttpClient client = new DefaultHttpClient();

    @Override
    public void onCreate() {
        // TODO Auto-generated method stub
        super.onCreate();
        CookieSyncManager.createInstance(this);
        cookieStore = new BasicCookieStore();
        localContext = new BasicHttpContext();
        localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
    }
    ...
}

And I have a connection in Runnable parts:

HttpURLConnection conn = null;
URL url;
try {
    url = new URL(requestUrl);
    conn = (HttpURLConnection) url.openConnection();                
    if (Integer.parseInt(Build.VERSION.SDK) < Build.VERSION_CODES.FROYO) {
        System.setProperty("http.keepAlive", "false");
    }
    conn.setConnectTimeout(8000);
    conn.setRequestMethod(method);
    conn.setInstanceFollowRedirects(false);
    conn.setRequestProperty("Content-Type","application/x-www-form-urlendcoded");

    MyApplication app = (MyApplication) mContext.getApplicationContext();

*******************************************     
    if(app.cookieStore.getCookies()!=null){
        conn.setRequestProperty("Cookie", app.cookieStore.getCookies().toString());
        Log.d("tag", "cookie get " +  cookie.getCookie(mContext.getString(R.string.host_url))); 
    }   
********** this part not work **********    


    Map m = conn.getHeaderFields();
    if (m.containsKey("Set-Cookie")) {
        String cookies = "";
        Collection c = (Collection) m.get("Set-Cookie");
        for (Iterator i = c.iterator(); i.hasNext();) {
            cookies += (String) i.next() + ",";
        }
        cookie.setCookie(mContext.getString(R.string.host_url), cookies);
        Log.d("tag", "cookie set " +  cookies);
    }   
} catch(...) { ... }

I get Cookiee by using cookieStore and also set cookies, but I get nothing, it returns null.
How use CookieStore?

Some example and answer give this:

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

It also returns null for me.


回答1:


Use this to set cookies.

First, set upcookieManager:

    cookieManager = new java.net.CookieManager();
    CookieHandler.setDefault(cookieManager);
    cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);

Next, set cookies to HttpUrlConnection by setRequestProperty()

        if (cookieManager.getCookieStore().getCookies().size() > 0) {

            List<HttpCookie> cookies = cookieManager.getCookieStore().getCookies();

            if (cookies != null) {
                for (HttpCookie cookie : cookies) {
                    conn.setRequestProperty("Cookie", cookie.getName() + "=" + cookie.getValue());
                }
            }
        }



回答2:


set cookie :

conn.setRequestProperty("Cookie", "cookieName=cookieValue; domain=www.test.com");

get cookie :

Map<String, List<String>> headerFields = conn.getHeaderFields();
List<String> cookiesHeader = headerFields.get("Set-Cookie");
if(cookiesHeader != null){
    String cookie = cookiesHeader.get(0);
    HttpCookie httpCookie = HttpCookie.parse(cookie).get(0);
    String name = httpCookie.getName(); 
    String value = httpCookie.getValue();
    String domain = httpCookie.getDomain();
}


来源:https://stackoverflow.com/questions/10814462/how-to-get-cookies-in-httpurlconnection-by-using-cookiestore

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!