2014-07-20 60 views
1

祝您有美好的一天!我是新來的Java。我用java編寫了一個程序來登錄到一個HTTP PHP網站。當我運行程序時,它不會登錄。它只是顯示初始登錄頁面本身的內容,而不是登錄後出現的頁面。我不知道我的錯誤是什麼。我在網上以及在這個網站上搜索了很多。但對我來說沒有運氣。 。:(編寫一個java程序登錄到HTTP PHP網站

這是我的計劃,請讓我知道,如果有在任何錯誤

import java.io.BufferedReader; 
import java.io.DataOutputStream; 
import java.io.InputStreamReader; 
import java.io.UnsupportedEncodingException; 
import java.net.CookieHandler; 
import java.net.CookieManager; 
import java.net.URL; 
import java.net.URLEncoder; 
import java.util.ArrayList; 
import java.util.List; 
import java.net.HttpURLConnection; 
import org.jsoup.Jsoup; 
import org.jsoup.nodes.Document; 
import org.jsoup.nodes.Element; 
import org.jsoup.select.Elements; 

public class HttpUrlConnectionExample1 { 

    private List<String> cookies; 
    private HttpURLConnection conn; 

    private final String USER_AGENT = "Mozilla/5.0"; 

    public static void main(String[] args) throws Exception { 

    String url = "http://www.iwhatgroups.com/log%20in.php"; 
    String email = "http://www.iwhatgroups.com"; 

    HttpUrlConnectionExample1 http = new HttpUrlConnectionExample1(); 

    // make sure cookies is turn on 
    CookieHandler.setDefault(new CookieManager()); 

    // 1. Send a "GET" request, so that you can extract the form's data. 
    String page = http.GetPageContent(url); 
    String postParams = http.getFormParams(page, "MyUserId", "MyPassWord"); 

    // 2. Construct above post's content and then send a POST request for 
    // authentication 
    http.sendPost(url, postParams); 

    // 3. success then go to email. 
    String result = http.GetPageContent(email); 
    System.out.println(result); 
    } 

    private void sendPost(String url, String postParams) throws Exception { 

    URL obj = new URL(url); 
    conn = (HttpURLConnection) obj.openConnection(); 

    // Acts like a browser 
    conn.setUseCaches(false); 
    conn.setRequestMethod("POST"); 
    conn.setRequestProperty("Host", "iwhatgroups.com"); 
    conn.setRequestProperty("User-Agent", USER_AGENT); 
    // conn.setRequestProperty("Accept", 
    //  "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"); 
    // conn.setRequestProperty("Accept-Language", "en-US,en;q=0.5"); 
    // for (String cookie : this.cookies) { 
    //  conn.addRequestProperty("Cookie", cookie.split(";", 1)[0]); 
    // } 
    // conn.setRequestProperty("Connection", "keep-alive"); 
    conn.setRequestProperty("Referer", "http://iwhatgroups.com"); 
    // conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 
    // conn.setRequestProperty("Content-Length", Integer.toString(postParams.length())); 

    conn.setDoOutput(true); 
    conn.setDoInput(true); 

    // Send post request 
    DataOutputStream wr = new DataOutputStream(conn.getOutputStream()); 
    wr.writeBytes(postParams); 
    wr.flush(); 
    wr.close(); 

    int responseCode = conn.getResponseCode(); 
    System.out.println("\nSending 'POST' request to URL : " + url); 
    System.out.println("Post parameters : " + postParams); 
    System.out.println("Response Code : " + responseCode); 

    BufferedReader in = 
     new BufferedReader(new InputStreamReader(conn.getInputStream())); 
    String inputLine; 
    StringBuffer response = new StringBuffer(); 

    while ((inputLine = in.readLine()) != null) { 
     response.append(inputLine); 
    } 
    in.close(); 
    // System.out.println(response.toString()); 

    } 

    private String GetPageContent(String url) throws Exception { 

    URL obj = new URL(url); 
    conn = (HttpURLConnection) obj.openConnection(); 

    // default is GET 
    conn.setRequestMethod("GET"); 

    conn.setUseCaches(false); 

    // act like a browser 
    conn.setRequestProperty("User-Agent", USER_AGENT); 
    conn.setRequestProperty("Accept", 
     "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"); 
    conn.setRequestProperty("Accept-Language", "en-US,en;q=0.5"); 
    if (cookies != null) { 
     for (String cookie : this.cookies) { 
      conn.addRequestProperty("Cookie", cookie.split(";", 1)[0]); 
     } 
    } 
    int responseCode = conn.getResponseCode(); 
    System.out.println("\nSending 'GET' request to URL : " + url); 
    System.out.println("Response Code : " + responseCode); 

    BufferedReader in = 
     new BufferedReader(new InputStreamReader(conn.getInputStream())); 
    String inputLine; 
    StringBuffer response = new StringBuffer(); 

    while ((inputLine = in.readLine()) != null) { 
     response.append(inputLine); 
     System.out.println(inputLine); 
    } 
    in.close(); 

    // Get the response cookies 
    setCookies(conn.getHeaderFields().get("Set-Cookie")); 

    return response.toString(); 

    } 

    public String getFormParams(String html, String username, String password) 
     throws UnsupportedEncodingException { 

    System.out.println("Extracting form's data..."); 

    Document doc = Jsoup.parse(html); 

    // Form id 
    Element loginform = doc.getElementById("mainBody"); 
    Elements inputElements = loginform.getElementsByTag("div"); 
    List<String> paramList = new ArrayList<String>(); 
    for (Element inputElement : inputElements) { 
     String key = inputElement.attr("name"); 
     String value = inputElement.attr("value"); 

     if (key.equals("inputEmail")) 
      value = username; 
     else if (key.equals("inputPassword")) 
      value = password; 
     paramList.add(key + "=" + URLEncoder.encode(value, "UTF-8")); 
    } 

    // build parameters list 
    StringBuilder result = new StringBuilder(); 
    for (String param : paramList) { 
     if (result.length() == 0) { 
      result.append(param); 
     } else { 
      result.append("&" + param); 
     } 
    } 
    return result.toString(); 
    } 

    public List<String> getCookies() { 
    return cookies; 
    } 

    public void setCookies(List<String> cookies) { 
    this.cookies = cookies; 
    } 

} 

謝謝大家閱讀或回答這個

注意:如果我取消調用setRequestProperty它引發NullPointerException異常,否則(我的意思是,如果我評論他們)它給人的登錄頁面。請儘可能幫助我。

再次感謝。

+0

如果您使用的是jsoup,那麼您可以通過執行類似http://stackoverflow.com/questions/6432970/jsoup-posting-and-cookie來簡化您的代碼 – Pshemo

回答

0

的PROBL ems在這裏可能會很多。 - GET調用中無重定向處理 - POST調用錯誤的URL - 缺少標頭參數。

我建議您使用Firebug並用瀏覽器進行調試,以執行登錄。有時,使用JavaScript處理登錄,真正的POST URL可能與登錄頁面的URL不同。