2012-09-12 97 views
2

我正在嘗試使用httpclient登錄到https url,但failed.can我得到了解決方案,我的問題?這是我編寫的代碼。這個代碼能夠獲取cookie部分,但它沒有得到登錄。在登錄後,我需要從登錄頁面獲取一些數據。使用httpclient登錄到https網址java

DefaultHttpClient httpclient = new DefaultHttpClient(); 
    HttpGet httpget = new HttpGet("http://www.example.com"); 
    HttpResponse response = httpclient.execute(httpget); 
     HttpEntity entity = response.getEntity(); 
    System.out.println("Initial set of cookies:"); 
     List<Cookie> cookies = httpclient.getCookieStore().getCookies(); 
     if (cookies.isEmpty()) { 
      System.out.println("None"); 
     } else { 
      for (int i = 0; i < cookies.size(); i++) { 
       System.out.println("- " + cookies.get(i).toString()); 
      } 
     } 

     HttpPost httpost = new HttpPost("https://www.example.com/jsp/login.jsp"); 

     List <NameValuePair> nvps = new ArrayList <NameValuePair>(); 
     nvps.add(new BasicNameValuePair("username", "xxx")); 
     nvps.add(new BasicNameValuePair("password", "xxx")); 

     httpost.setEntity(new UrlEncodedFormEntity(nvps, Consts.UTF_8)); 

     response = httpclient.execute(httpost); 
     entity = response.getEntity(); 

     System.out.println("Login form get: " + response.getStatusLine()); 
     EntityUtils.consume(entity); 

     System.out.println("Post logon cookies:"); 
     cookies = httpclient.getCookieStore().getCookies(); 
     if (cookies.isEmpty()) { 
      System.out.println("None"); 
     } else { 
      for (int i = 0; i < cookies.size(); i++) { 
       System.out.println("- " + cookies.get(i).toString()); 
      } 
     } 

回答

0

您可能會缺少登錄按鈕和幾個名稱值對。我不確定你的按鈕被調用的是什麼,或者與它一起發送的值。

List <NameValuePair> nvps = new ArrayList <NameValuePair>(); 
     nvps.add(new BasicNameValuePair("username", "xxx")); 
     nvps.add(new BasicNameValuePair("password", "xxx")); 
     nvps.add(new BasicNameValuePair("button", "Login")); 

我會下載TamperData,然後轉到您的網頁並登錄,同時TamperData到了。使用它來查看您登錄的POST。可能有一個名稱值對正在發送,而您錯過了。