private static CookieStore cookieStore = new BasicCookieStore();
private HttpClient client = new DefaultHttpClient();
private static HttpContext httpContext = new BasicHttpContext();
public static void main(String[] args) throws Exception {
String url = "http://www.codechef.com";
String account = "http://www.codechef.com/node?destination=node";
httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
List<NameValuePair> postParams = http.getFormParams();
sendPost(url, postParams);
}
private void sendPost(String url, List<NameValuePair> postParams)
throws Exception {
HttpPost post = new HttpPost(url);
post.setHeader("Accept","text/plain");
post.setHeader("Accept-Language", "en-US");
post.setHeader("Connection", "keep-alive");
post.setEntity(new UrlEncodedFormEntity(postParams));
HttpResponse response = client.execute(post,httpContext);
List<Cookie> cook=cookieStore.getCookies();
if(cook==null)
System.out.println("Null");
else{
System.out.println(cook.size());
for(Cookie c:cook){
String cookieReader=c.getName()+" = "+c.getValue()+";domain= "+c.getDomain();
System.out.println(cookieReader);
}
}
}
public List<NameValuePair> getFormParams() throws UnsupportedEncodingException {
List<NameValuePair> paramList = new ArrayList<NameValuePair>();
paramList.add(new BasicNameValuePair("name","name"));
paramList.add(new BasicNameValuePair("pass","pass"));
return paramList;
}在post方法之后,cookie的大小是0,但我在浏览器中检查了一下,它显示了sessionID cookie。但我无法使用此代码提取它来验证用户身份。谢谢。
发布于 2013-12-20 06:53:45
您应该注意HTML表单域。为了正确实现post过程,通常需要隐藏字段。
看看这个网站上的登录表单的html源代码(检查元素...)表单域是:"user","pass“加上两个隐藏的域"form_build_id”和"form_id“。
尝试在您的'getFormParams‘函数中添加以下内容:
paramList.add(new BasicNameValuePair("form_id","user_login_block"));https://stackoverflow.com/questions/20690661
复制相似问题