2013-12-19 32 views
0
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。但我無法使用此代碼提取它來驗證用戶身份。謝謝。Cookie未顯示(apache httpclient v4)

+0

一開始調試可能是打印的地方「response.getHeaders(‘曲奇’);」收到'回覆'後立即。也許甚至可以手動將它添加到CookieStore中,並查看'cookieStore.getCookies()'是否返回任何內容。 – andrel

+0

此外,當您檢查瀏覽器中收到的頭文件時,請確保不要混淆POST和GET(即:POST可能不會返回GET將返回的相同頭文件)。你可以插入一行打印出'response.getHeaders(「cookie」);'查看收到的實際cookie標頭。 – andrel

回答

0

您應該注意HTML表單域。 爲了正確完成後期處理,通常需要隱藏字段。

看看本網站的登錄表單的HTML源代碼(檢查元素...) 表單字段爲:「user」,「pass」加兩個隱藏字段「form_build_id」和「form_id」。

嘗試在「getFormParams」功能添加此:

paramList.add(new BasicNameValuePair("form_id","user_login_block")); 
相關問題