gpt4 book ai didi

java - Android HttpClient 和 Cookie

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:25:47 24 4
gpt4 key购买 nike

我在 Android 中遇到 HttpClient 问题:通过使用以下代码,我想通过 webview 登录来使用之前已经设置的 cookie。所以登录数据应该有,确实有,我测试过。但是当我在 httppost 或 httpget 中使用 cookie 时,它​​不使用登录数据。但是这些 cookie 实际上应该足以接收需要登录的页面,不是吗?我不太确定我是否需要以特殊方式将 cookie 发送到服务器,或者是否足以将其加载到 httpcontext 中。这是代码:

DefaultHttpClient httpclient = new DefaultHttpClient();
CookieStore lCS = new BasicCookieStore();


if (CookieManager.getInstance().getCookie(pUrl) != null) {
String cookieString = CookieManager.getInstance().getCookie(pUrl);

String[] urlCookieArray = cookieString.split(";");
for (int i = 0; i < urlCookieArray.length; i++) {
System.out.println(urlCookieArray[i]);
String[] singleCookie = urlCookieArray[i].split("=");
Cookie urlCookie = new BasicClientCookie(singleCookie[0], singleCookie[1]);
lCS.addCookie(urlCookie);
}

}

HttpContext localContext = new BasicHttpContext();
httpclient.setCookieStore(lCS);
localContext.setAttribute(ClientContext.COOKIE_STORE, lCS);

HttpPost httppost = new HttpPost(pUrl);


// get the url connection
try {

StringBuilder sb = new StringBuilder();
HttpResponse response = httpclient.execute(httppost, localContext);
InputStream is = response.getEntity().getContent();
InputStreamReader isr = new InputStreamReader(is);

如果我运行代码,我只会收到该站点的登录页面,因此它不接受 cookie。

提前感谢您的帮助

你好,蒂莫

最佳答案

我遇到了同样的问题,我使用了与问题中类似的方法,但没有成功。使它对我有用的是为每个复制的 cookie 添加域。(BasicClientCookie cookie.setDomain(String))

我的 util 函数:

public static BasicCookieStore getCookieStore(String cookies, String domain) {
String[] cookieValues = cookies.split(";");
BasicCookieStore cs = new BasicCookieStore();

BasicClientCookie cookie;
for (int i = 0; i < cookieValues.length; i++) {
String[] split = cookieValues[i].split("=");
if (split.length == 2)
cookie = new BasicClientCookie(split[0], split[1]);
else
cookie = new BasicClientCookie(split[0], null);

cookie.setDomain(domain);
cs.addCookie(cookie);
}
return cs;
}

String cookies = CookieManager.getInstance().getCookie(url);
BasicCookieStore lCS = getCookieStore(cookies, MyApp.sDomain);

HttpContext localContext = new BasicHttpContext();
DefaultHttpClient httpclient = new DefaultHttpClient();
httpclient.setCookieStore(lCS);
localContext.setAttribute(ClientContext.COOKIE_STORE, lCS);
...

关于java - Android HttpClient 和 Cookie,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13847102/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com