【发布时间】:2013-03-30 09:17:38
【问题描述】:
我尝试使用 Apache HttpClient 发送带有表单帖子的 cookie,但由于某种原因,服务器收到了请求,但没有收到 cookie。这是我的代码:
DefaultHttpClient client = new DefaultHttpClient();
// Set the cookies...
{
String Domain = MyGetParameter("Domain");
BasicCookieStore cookieStore = new BasicCookieStore();
String[] strs = GetParameterSplitted("PostCookies");
int size = strs.length;
for (int i=0; i<size-1; i+=2)
{
//JOptionPane.showMessageDialog(null, strs[i]+" = "+FromBase64(strs[i+1], "UTF-8"));
BasicClientCookie cookie = new BasicClientCookie(strs[i], FromBase64(strs[i+1], "UTF-8"));
cookie.setDomain(Domain);
cookie.setPath("/");
//cookie.setSecure(true);
cookieStore.addCookie(cookie);
}
client.setCookieStore(cookieStore);
}
HttpPost post = new HttpPost(url.toURI());
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(10);
// Set the form POST parameters...
{
String[] strs = GetParameterSplitted("PostParams");
int size = strs.length;
for(int i=0; i<size-1; i+=2)
{
String name = strs[i].trim();
String value = FromBase64(strs[i+1].trim(), "UTF-8");//, "UTF-8"
nameValuePairs.add(new BasicNameValuePair(name, value));
}
}
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
post.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
post.getParams().setParameter(ClientPNames.COOKIE_POLICY, org.apache.http.client.params.CookiePolicy.BROWSER_COMPATIBILITY);
HttpResponse response = client.execute(post);
int StatusCode = response.getStatusLine().getStatusCode();
该站点使用 HTTP(不是 HTTPS),我确保将域名正确设置为 cookie (http://mysite),并且在执行上述代码时,cookie 似乎设置正确。
有人知道为什么无法将它们传递给服务器吗? 我在这个网站上看到了其他类似的问题,但似乎没有任何帮助。
【问题讨论】:
-
您确定 cookie 来自您发送到的完全相同的域吗?例如
http://stackoverflow.com和http://www.stackoverflow.com是不同的域。 -
是的。实际上,如果 POST url 不同,我认为请求甚至不会到达服务器。我在本地调试站点。我将 cookie 域设置为
http://mysite,并将表单发布到mysite/blah/blah。我认为http://部分没有任何作用,是吗? -
是否需要这样设置路径:
cookie.setPath("/blah/blah");?
标签: java cookies httpclient