dongwen7371 2014-07-20 09:56
浏览 90

编写java程序登录HTTP PHP网站

Have a good day! I am new to java. I wrote a program in java to login to a HTTP PHP website. When I run the program it doesn't get logged in. It just displays the content of the initial login page itself and not the page that comes after logged in. I don't know what my mistake is. I have searched a lot in the web and in this website as well. But no luck for me. :(

This is my program. Please let me know if there is any error in it.

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("
Sending '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("
Sending '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;
  }

}

Thank you all for reading or answering this.

NOTE:If I uncomment setRequestProperty it throws NullPointerException. Otherwise (I mean if I comment them) it gives the login page. Please help me out if possible.

Thanks again.

  • 写回答

1条回答 默认 最新

  • drfqfuhej48511519 2014-12-16 10:00
    关注

    The problems here might be a lot. - No Redirect handling in GET call - Wrong URL for POST call - Missing header parameters.

    I would suggest you to use Firebug and debug with a browser a login performed by it.Sometimes the login is handled using JavaScript and the real POST URL might be different from the URL of the login page.

    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题