java 如何在 Android 上的活动之间将 HTTP 会话 cookie 保存在 HttpContext 中?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10738029/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to keep HTTP session cookies in HttpContext between activities on Android?
提问by uzer
Here is current simple description my app. It uses some remote server API, which uses standart HTTP session. Login activity. It calls auth class, passing login and password.
这是我的应用程序当前的简单描述。它使用一些使用标准 HTTP 会话的远程服务器 API。登录活动。它调用 auth 类,传递登录名和密码。
public class Auth extends AsyncTask{
...
private DefaultHttpClient client = new DefaultHttpClient();
private HttpContext localContext = new BasicHttpContext();
private CookieStore cookieStore = new BasicCookieStore();
...
public void auth(String login, String password) {
localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
HttpPost request = new HttpPost(url);
...
}
protected void onPostExecute(Boolean result){
parent.loginresponse(result)
}
On successful auth, remote server creates standart HTTP session, sending me cookie, saved in CookiStore. After login, loginresponse starts main activity. There I wish to have one universal class for all API requests.
成功验证后,远程服务器创建标准 HTTP 会话,向我发送 cookie,保存在 CookieStore 中。登录后,loginresponse 开始主要活动。我希望为所有 API 请求创建一个通用类。
How do I make correct keeping alive HTTP session information, created after login, between all activities, and passing it to needed functions for corresponding API methods?
如何使登录后创建的 HTTP 会话信息在所有活动之间正确保持活动状态,并将其传递给相应 API 方法所需的函数?
回答by OrhanC1
回答by jeb_is_a_mess
You can use a singleton class that would look something like this:
您可以使用如下所示的单例类:
public class UserSession
{
private static UserSession sUserSession;
/*
The rest of your class declarations...
*/
public get(){
if (sUserSession == null)
{
sUserSession = new UserSession();
}
return sUserSession;
}
}
Once an instance of this class is initialized, it will stay in memory.
一旦这个类的实例被初始化,它就会留在内存中。
回答by nikki
You can do something like the following:
您可以执行以下操作:
HttpClient client = getNewHttpClient();
// Create a local instance of cookie store
CookieStore cookieStore = new BasicCookieStore();
// Create local HTTP context
HttpContext localContext = new BasicHttpContext();
// Bind custom cookie store to the local context
localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
try {
request = new HttpPost(url);
// request.addHeader("Accept-Encoding", "gzip");
} catch (Exception e) {
e.printStackTrace();
}
if (postParameters != null && postParameters.isEmpty() == false) {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
postParameters.size());
String k, v;
Iterator<String> itKeys = postParameters.keySet().iterator();
while (itKeys.hasNext()) {
k = itKeys.next();
v = postParameters.get(k);
nameValuePairs.add(new BasicNameValuePair(k, v));
}
UrlEncodedFormEntity urlEntity = new UrlEncodedFormEntity(
nameValuePairs);
request.setEntity(urlEntity);
}
try {
Response = client.execute(request, localContext);
HttpEntity entity = Response.getEntity();
int statusCode = Response.getStatusLine().getStatusCode();
Log.i(TAG, "" + statusCode);
Log.i(TAG, "------------------------------------------------");
if (entity != null) {
Log.i(TAG,
"Response content length:" + entity.getContentLength());
}
List<Cookie> cookies = cookieStore.getCookies();
for (int i = 0; i < cookies.size(); i++) {
Log.i(TAG, "Local cookie: " + cookies.get(i));
}
try {
InputStream in = (InputStream) entity.getContent();
// Header contentEncoding =
// Response.getFirstHeader("Content-Encoding");
/*
* if (contentEncoding != null &&
* contentEncoding.getValue().equalsIgnoreCase("gzip")) { in =
* new GZIPInputStream(in); }
*/
BufferedReader reader = new BufferedReader(
new InputStreamReader(in));
StringBuilder str = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
Log.i(TAG, "" + str.append(line + "\n"));
}
in.close();
response = str.toString();
Log.i(TAG, "response" + response);
} catch (IllegalStateException exc) {
exc.printStackTrace();
}
} catch (Exception e) {
Log.e("log_tag", "Error in http connection " + response);
} finally {
// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate deallocation of all system resources
// client.getConnectionManager().shutdown();
}
return response;
enter code here