I'm using Apache HttpClient 4 in Java.
Why doesn't HttpClient send the Cookie that's set by the response of "request" to 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-Agen开发者_如何转开发t", "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));
}
I used Fiddler2 to view the traffic, and when I compare the Post from my code to the one from Firefox I don't see any differences, except that my code doesn't send the cookie.
Because you are getting the cookie from http://www.websitename.de, but try to access http://websitename.de later on. This is not the same host name.
@Jochen has identified the likely cause. This is fundamental HTTP cookie behavior. By default, cookies are only sent to the site that set them ... for security and privacy reasons.
If you want to work around this you should do one of the following:
- Make sure that the URL hostname and port are the same.
- Get the web server to set the cookie with a Domain attribute of ".websitename.de". However, this has significant security implications in that the cookie will be sent with requests to all subdomains of "websitename.de" ... for other users accessing the site using normal web browsers.
- Create / configure a CookieStore that will ignore the normal rules and send the cookie to "www.websitename.de" as well. (Presumably, you know what you are doing and this isn't a security risk ...)
精彩评论