2011-11-26 52 views
2

所以這是目前我的應用程序如何設置:接受所有Cookie通過HttpClient

1.)登錄活動。 2.)一旦登錄,其他活動可能會啓動,使用PHP腳本,需要從登錄發送的Cookie。

我在我的應用程序中使用一個HttpClient以確保使用相同的cookie,但我的問題是我得到3個被拒絕的cookies中的2個。我不在乎cookies的有效性,但我確實需要他們接受。 I tried setting the CookiePolicy,但那也沒有奏效。這是logcat的是說:

11-26 10:33:57.613: WARN/ResponseProcessCookies(271): Cookie rejected: "[version: 0]  [name: cookie_user_id][value: 1][domain: www.trackallthethings.com][path: trackallthethings][expiry: Sun Nov 25 11:33:00 CST 2012]". Illegal path attribute "trackallthethings". Path of origin: "/mobile-api/login.php" 

11-26 10:33:57.593: WARN/ResponseProcessCookies(271): Cookie rejected: "[version: 0][name: cookie_session_id][value: 1985208971][domain: www.trackallthethings.com][path: trackallthethings][expiry: Sun Nov 25 11:33:00 CST 2012]". Illegal path attribute "trackallthethings". Path of origin: "/mobile-api/login.php" 

我相信,我的實際代碼是正確的(我的應用程序仍然登錄正確的,只是不接受上述餅乾),但在這裏它是無論如何:

HttpGet httpget = new HttpGet(//MY URL); 
HttpResponse response; 
response = Main.httpclient.execute(httpget); 
HttpEntity entity = response.getEntity(); 
InputStream in = entity.getContent(); 

BufferedReader reader = new BufferedReader(new InputStreamReader(in)); 
StringBuilder sb = new StringBuilder(); 

從這裏我使用StringBuilder來獲取響應的字符串。沒有什麼花哨。

我知道我的cookies被拒絕的原因是因爲「非法路徑屬性」(我在/mobile-api/login.php上運行腳本,而cookie將返回路徑爲「/ 「對於trackallthethings),但我想無論如何接受餅乾。有沒有辦法做到這一點?

回答

7

您面臨的問題似乎是出於隱私/安全目的而設計的。一般來說,任何資源都不允許設置它將無法接收的cookie。在這裏,您嘗試使用資源/mobile-api/login.php中的路徑trackallthethings設置cookie,該路徑顯然不起作用。

在這裏你有以下兩種選擇

  1. 設置與這對雙方的資源訪問的路徑餅乾(這可能是根'/')OR
  2. 定義自定義的cookie政策並註冊自己的cookie支持。這裏是related documentationexample

希望這會有所幫助。

+0

這絕對是正確的答案。我以爲我做錯了什麼,但事實證明,我的項目合作伙伴正在用不正確的路徑發放cookie。 :-) – Vinay

2

由於HttpClient的API似乎非常快的變化,這裏是HttpClient 4.5.1一些工作示例代碼,允許所有(畸形)的cookie:

class EasyCookieSpec extends DefaultCookieSpec { 
    @Override 
    public void validate(Cookie arg0, CookieOrigin arg1) throws MalformedCookieException { 
     //allow all cookies 
    } 
} 

class EasySpecProvider implements CookieSpecProvider { 
    @Override 
    public CookieSpec create(HttpContext context) { 
     return new EasyCookieSpec(); 
    } 
} 

Registry<CookieSpecProvider> r = RegistryBuilder.<CookieSpecProvider>create() 
      .register("easy", new EasySpecProvider()) 
      .build(); 

CookieStore cookieStore = new BasicCookieStore(); 

RequestConfig requestConfig = RequestConfig.custom() 
      .setCookieSpec("easy") 
      .build(); 

CloseableHttpClient httpclient = HttpClients.custom() 
      .setDefaultCookieStore(cookieStore) 
      .setDefaultCookieSpecRegistry(r) 
      .setDefaultRequestConfig(requestConfig) 
      .build(); 
+0

我遇到了這個代碼的問題。它似乎不允許所有格式不正確的Cookie。例如,我在使用簡單的Java Date類時提供了一些認證令牌的'Invalid'expires'屬性'異常。 '週六,2017年09月16日20:06:21 GMT'>作品 '2017年3月24日星期五20:46:08 GMT'>不起作用 – po3t