如何解决如何在Android应用中使用HTTP cookie?
| 我正在尝试维护我的Android应用程序和Drupal网站之间的登录用户会话。在我的研究中,归结为将cookie发送回Drupal,但我正在努力实现它。我该如何开始呢?解决方法
万一其他人遇到相同的问题,我也遇到类似的问题,我可以通过以下代码解决它:
1-在您的课程中定义CookieManager和CookieStore
CookieManager cookieManager;
CookieStore cookieStore;
2-添加默认的Cookie处理程序,例如在类构造函数中或在OnCreate方法中
cookieManager = new CookieManager();
CookieHandler.setDefault(cookieManager);
3-当您执行HTTP请求时使用cookie存储
public byte[] openURI(String uri) {
try {
URI uriObj = new URI(uri);
DefaultHttpClient client = new DefaultHttpClient();
// Use the cookieStor with the request
if (cookieStore == null) {
cookieStore = client.getCookieStore();
} else {
client.setCookieStore(cookieStore);
}
HttpGet getRequest = new HttpGet(uriObj);
HttpResponse response = client.execute(getRequest);
// Read the response data
InputStream instream = response.getEntity().getContent();
int contentLength = (int) response.getEntity().getContentLength();
byte[] data = new byte[contentLength];
instream.read(data);
response.getEntity().consumeContent();
return data ;
} catch (URISyntaxException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
, 我非常确定,如果您使用Android API随附的HttpClient,它将在您手动关闭连接之前为您执行cookie会话管理。
如果我错了,那么可以通过使用CookieStore接口或BasicCookieStore类实现自己的cookie存储,轻松解决此问题。如果所有其他方法均失败,则可以手动存储cookie,并在每次发出HTTP请求时在标题中设置cookie。
我不确定这是否会针对您的特定问题而改变,但是考虑到您对问题的描述,这很可能会起作用。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。