我尝试使用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。
有没有人知道为什么它没有将它们传递给服务器? 我在这个网站上看到过其他类似的问题,但似乎没有任何帮助。
答案 0 :(得分:16)
仔细观察,如果您的Cookie的日期已过期,则httptClient不会发送此Cookie,此时您应该将Cookie设置为日期。
并且在域名中将没有“http://”,只是简单的域名。
例如:(http://www.gmail.com =&gt;这样写 setDomain(“www.gmail.com”))
此示例我将100天添加到当天并设置cookie。 示例通过带有cookie的HttpClient发送帖子数据:
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DAY_OF_YEAR, 100);
Date date = calendar.getTime();
DefaultHttpClient httpClient = new DefaultHttpClient();
httpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY,CookiePolicy.BROWSER_COMPATIBILITY);
httpClient.setCookieStore(new BasicCookieStore());
BasicClientCookie cookie = new BasicClientCookie(YourCookieName, YourCookieValue);
cookie.setDomain(YourDomain);
cookie.setExpiryDate(date);
cookie.setPath("/");
httpClient.getCookieStore().addCookie(cookie);
....
httpClient.execute(yourHttpUriRequest);