0

我知道我做错了;我不知道如何正确地做到这一点。这是 Apache servlet 的一小段代码。

@覆盖

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.                
4

1 回答 1

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 从 String 转换回 List

于 2013-10-26T09:38:11.310 回答