【问题标题】:Android BasicCookieStore, Cookies and HttpGetAndroid BasicCookieStore、Cookies 和 HttpGet
【发布时间】:2012-11-25 23:30:09
【问题描述】:

我有一个应用程序,它应该向 URL 发送 GET 请求并发送一些 cookie。我一直在查看 BasicCookieStore 和 Cookie 类的一些代码示例,但我无法弄清楚如何使用它们。谁能指出我正确的方向?

【问题讨论】:

    标签: java android cookies http-get cookiestore


    【解决方案1】:

    要使用 cookie,您需要以下内容:

    CookieStore cookieStore = new BasicCookieStore();
    DefaultHttpClient httpclient = new DefaultHttpClient();
    
    HttpContext ctx = new BasicHttpContext();
    ctx.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
    HttpGet get = new HttpGet("your URL here");
    
    HttpResponse response = httpclient.execute(get,ctx);
    

    如果您想在请求之间保留 cookie,则必须为每个请求重用 cookieStorectx

    另外,您可以阅读您的cookieStore 以了解其中的内容:

    List<Cookie> cookies = cookieStore.getCookies();
    if( !cookies.isEmpty() ){
        for (Cookie cookie : cookies){
            String cookieString = cookie.getName() + " : " + cookie.getValue();
            Log.info(TAG, cookieString);
        }
    }
    

    【讨论】:

    • 也许我还没有完全理解 cookie 的概念,但是我有两个字符串,我想将它们作为名称-值对发送到 url。从这段代码中,我无法理解如何做到这一点。你能指导我吗?
    • @RameezHussain 你可以使用addCookie()CookieStore 方法:developer.android.com/reference/org/apache/http/client/…
    猜你喜欢
    • 1970-01-01
    • 2014-10-28
    • 1970-01-01
    • 2016-08-30
    • 1970-01-01
    • 2014-11-16
    • 1970-01-01
    • 1970-01-01
    • 2023-03-15
    相关资源
    最近更新 更多