2011-05-14 84 views
3

我在Java中使用Apache HttpClient 4。
爲什麼HttpClient不會將由「請求」響應設置的Cookie發送到post1?爲什麼HttpClient不發送我的Cookie?

public static void goDoIt() throws ClientProtocolException, IOException { 

    HttpClient client = new DefaultHttpClient(); 
    //for use with Fiddler2 
    HttpHost proxy = new HttpHost("127.0.0.1", 8888); 
    client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); 
    //stores all cookies automatically (should sent them too(?)) 
    CookieStore cookieStore = new BasicCookieStore(); 
    HttpContext localContext = new BasicHttpContext(); 
    localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore); 

    HttpGet request = new HttpGet("http://www.websitename.de"); 
    request.addHeader("Host", "hosthost.de"); 
    request.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.0; rv:2.0.1) Gecko/20100101 Firefox/4.0.1"); 

    //required to fetch Cookie 1, stored automatically 
    HttpResponse response1 = client.execute(request, localContext); 
    request.abort(); 

    // parameters and headers 
    List<NameValuePair> parameters1 = new ArrayList<NameValuePair>(); 
    parameters1.add(new BasicNameValuePair("username", "karl")); 
    parameters1.add(new BasicNameValuePair("age", "23")); 
    parameters1.add(new BasicNameValuePair("button","button")); 

    HttpPost post1 = new HttpPost("http://websitename.de/Default.aspx"); 

    post1.addHeader("Host","hosthost.de"); 
    post1.addHeader("User-Agent", 
      "Mozilla/5.0 (Windows NT 6.0; rv:2.0.1) Gecko/20100101 Firefox/4.0.1"); 
    post1.addHeader("Referer","http://websitename.de/Default.aspx"); 

    UrlEncodedFormEntity entity1 = new UrlEncodedFormEntity(parameters1); 
    post1.setEntity(entity1); 


    // execute and print 
    HttpResponse response2 = client.execute(post1,localContext); 
    HttpEntity entity2 = response2.getEntity(); //fiddler doesn't show that the cookie is being sent ! 

    System.out.println(EntityUtils.toString(entity2)); 
} 

我使用Fiddler2來查看流量,當我從我的代碼從Firefox比較後到一個我看不出有什麼差別,只是我的代碼不發送的cookie。

回答

2

@Jochen已經確定了可能的原因。這是基本的HTTP cookie行爲。默認情況下,僅出於安全和隱私的原因,Cookie纔會發送到設置它們的網站。

如果你想解決這個你應該做下列之一:

  • 確保URL主機名和端口是相同的。
  • 獲取Web服務器以設置具有「.websitename.de」域屬性的Cookie。但是,這具有重大的安全隱患,因爲Cookie將以「websitename.de」的所有子域名的請求發送......對於使用普通Web瀏覽器訪問該站點的其他用戶。
  • 創建/配置一個CookieStore,它將忽略常規規則並將Cookie發送到「www.websitename.de」。 (據推測,你知道你在做什麼,這不是安全風險...)