为什么HttpClient不发送我的Cookie?

时间:2011-05-14 22:43:26

标签: java cookies post request httpclient

我在Java中使用Apache HttpClient 4 为什么HttpClient不会将“请求”响应设置的Cookie发送到post1?

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 个答案:

答案 0 :(得分:7)

因为您从http://www.websitename.de获取了Cookie,但稍后尝试访问http://websitename.de。这与主机名不同。

答案 1 :(得分:2)

@Jochen确定了可能的原因。这是基本的HTTP cookie行为。默认情况下,出于安全和隐私原因,cookie仅发送到设置它们的网站。

如果您想解决此问题,请执行以下操作之一:

  • 确保URL主机名和端口相同。
  • 获取Web服务器以使用Domain属性“.websitename.de”设置cookie。但是,这会产生重大的安全隐患,因为cookie将通过“websitename.de”的所有子域的请求发送给其他使用普通Web浏览器访问该站点的用户。
  • 创建/配置将忽略常规规则的CookieStore,并将cookie发送到“www.websitename.de”。 (据推测,你知道你在做什么,这不是安全隐患......)