如何在Android和/或Java中使用HttpClient管理cookie?

如何在Android和/或Java中使用HttpClient管理cookie?

我试图登录到一个站点并维护该会话/ cookie,以便服务器能够识别我的登录名,但是我正在努力寻找一种从响应中提取cookie并将其设置为保持我的登录名的请求的方法。我想知道是否应该使用标题“ Set-Cookie”或使用CookieStore。任何帮助是极大的赞赏。这是我的代码,并附有注释,我认为getHeader / getCookie方法可以使用。


public class Http

{

DefaultHttpClient client = new DefaultHttpClient();

HttpGet request;

HttpEntity entity;

HttpResponse response;

HttpPost post;

CookieStore cookieStore = new BasicCookieStore();

HttpContext localContext = new BasicHttpContext();


public static void setContext()

{

    localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);

}


public static void getPage(String url) throws Exception

{

    request = new HttpGet(url);

    response = client.execute(request, localContext);

    PARSER.preParse(url, response);

}


public static HttpResponse postPage(List<NameValuePair> params, String host, String action) throws Exception

{

    post = new HttpPost(host + action);

    post.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));


    response = client.execute(post, localContext);


    entity = response.getEntity();

    if(entity != null)

    {

        entity.consumeContent();

    }


    return response;

}



public void destoyHttp()

{

    client.getConnectionManager().shutdown();

}

}

为了希望其他人能更好地理解我的困惑,我添加了我知道确实可以正常工作并维护会话的代码,但是当我尝试将代码移至我的实际应用程序中时,它陷入了混乱。


素胚勾勒不出你
浏览 607回答 4
4回答

慕村225694

对我来说,这是行不通的,直到我使HttpContext和CookieStore都保持静态,以保留所有请求。

慕尼黑的夜晚无繁华

我设法使用Header []对象并成功设置了包括Cookie标头的标头,但这似乎并不能解决我的问题。我已经用我所做的代码编辑了我的问题,但是由于某种原因,当我将其移到我的实际应用程序时,它坏了。仅供参考,工作代码对标头不执行任何操作,就可以了吗?大声笑
打开App,查看更多内容
随时随地看视频慕课网APP