2013-10-26 27 views
0

我知道的是我在做它错误;我不知道怎么做才对。 以下是Apache servlet的一些代码。从Apache到Android应用程序的Cookie

@覆盖

protected void doGet(HttpServletRequest request, HttpServletResponse response) 
throws ServletException, IOException { 
response.setContentType("application/Cookie");// May be wrong 
Cookie c = new Cookie("cookie", "CookieS i LOVE"); 
c.setMaxAge(60*60);response.addCookie(c); 
     } 
For Android app i have this code to get the cookie sent from the that servlet. 
Now i want to store that cookie on my android device. and then retrieve it for 
another activities. 



{....} 
    public void onClick(View v) { 
    HttpClient client = new DefaultHttpClient(); 
    HttpGet httpget = new HttpGet("http://********:8080/***/servlet"); 
    Cookie c = (Cookie) CookiePolicy.ACCEPT_ALL; 
    try { 
    HttpResponse execute = client.execute(httpget); 
    } catch (ClientProtocolException e) { 
    e.printStackTrace(); 
    } catch (IOException e) { 
    e.printStackTrace(); 
    } 
    List<Cookie> cookies = ((AbstractHttpClient)client).getCookieStore() 
    .getCookies();   
    String mycookie = cookies.toString(); 
    Toast.makeText(Cookies.this, mycookie, Toast.LENGTH_SHORT).show(); 
    } 
    } 
    }   
    Thank You for your help.     
+0

'然后检索另一个activities'意味着同一个应用程序,但不同的活动或不同applicaitons? –

+0

是的,它是登录,所以第一个屏幕是注册的东西,其余的屏幕是出于商业目的。 –

回答

0

使用SharedPreferences存储cookie:

private SharedPreferences.Editor mEditor = null; 
private SharedPreferences pref = null; 

... 
mEditor = PreferenceManager.getDefaultSharedPreferences(this).edit(); 

... 

mCookies = httpclient.getCookieStore().getCookies(); 

if (mCookies.isEmpty()) { 
    Log.d("test_runner", "Cookies: None"); 
} 
else { 
for (int i = 0; i < mCookies.size(); i++) { 
    mEditor.putString("Cookies_" + i, mCookies.get(i).toString()); 
} 
    mEditor.commit(); 
} 

现在在其他活动那样称呼他们:

pref = PreferenceManager.getDefaultSharedPreferences(this); 

String cookies =pref.getString("Cookies_0", ""); 

.... 

作为一个侧面说明

我会使用Gson库将Cookies列表转换为字符串,并在首选项中存储代表所有Cookie的一个值。

后,对提取,转换与GSON从字符串返回列表

+0

谢谢Maxim Shoustin,如果我想使用CookieStore来存储这些cookie并通过CookieManager获取它们,这是可能的。 –

+0

如果您使用相同的应用程序,当然可以使用CookieManager的实例。但在活动结束后请记住,所有信息都重置。所以你可以投入服务,使其在后台运行或使用我的方式。 –

相关问题