Cookie not showing (apache httpclient v4)


  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,但我从浏览器中检查,它显示了会话 ID cookie。但是我无法使用此代码提取它来对用户进行身份验证。谢谢。

您应该注意HTML表单字段。为了正确实现后期处理,通常需要隐藏字段。

看看这个网站上登录表单的html来源(检查元素...表单字段包括:"用户"、"通过"以及两个隐藏字段"form_build_id"和"form_id"。

尝试在"getFormParams"函数中添加以下内容:

paramList.add(new BasicNameValuePair("form_id","user_login_block"));

最新更新