试图保存 cookie 的值来存储设备中的存储,但不是每次我再次启动应用程序时返回 null 值,我不知道为什么我们不存储 cookie 的值。
final HttpUriRequest request = new HttpGet(uri);
request.setHeader("User-Agent", Sonora.USER_AGENT);
try {
DefaultHttpClient client = new DefaultHttpClient();
if(cookieValue != null) {
Log.d(TAG,"COOKIE RECEBIDO E ARMAZENADO");
request.setHeader("Cookie", cookieName + "=" + cookieValue);
}
HttpResponse resp = client.execute(request);
// Check if server response is valid
StatusLine status = resp.getStatusLine();
if (status.getStatusCode() != Sonora.HTTP_STATUS_OK) {
Log.e(TAG, "HTTP error, invalid server status code: " + resp.getStatusLine());
return;
}
final List<Cookie> cookies = client.getCookieStore().getCookies();
int count = cookies.size();
for( int i = 0; i < count; i++ ) {
final Cookie c = cookies.get(i);
if ( c.getName().compareTo( cookieName ) == 0 ) {
cookieValue = c.getValue();
break;
}
}
} catch (IOException e) {
Log.e(TAG, "IOError error", e);
}
最佳答案
Android CookieStore 类不是持久性的 - 因此您的 cookie 不会保存在任何地方,并且会在您的应用程序停止时丢失。
您可以使用 Android 异步 Http 客户端 (http://loopj.com/android-async-http/),它支持您应用的 SharedPreferences 中的可选持久 cookie 存储。或者您可以根据 How to make persistent Cookies with a DefaultHttpClient in Android? 实现您自己的持久性 cookie 类.
关于Android 如何从响应的 DefaultHttpClient 保存 cookie?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8809251/