0

我一直在尝试让此代码正常工作,以便它可以向网站发送帖子以让我登录。我不确定我的 java 代码或我理解如何阅读的方式是否有问题html代码。

import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;

public class LogIn {
  public static void main(String[] args) {
    String url = "http://www.example.com/login.phtml";

try {

  String destination = "%2Findex.phtml";
  String username = "myUser";
  String password = "myPass";
  String submit = "Log In!";

  String destination_param = "destination";
  String username_param = "username";
  String password_param = "password";
  String submit_param = "submit";

  String encoded_destination = destination_param + "=" + URLEncoder.encode(destination, "UTF-8");
  String encoded_username = username_param + "=" + URLEncoder.encode(username, "UTF-8"); 
  String encoded_password = password_param + "=" + URLEncoder.encode(password, "UTF-8");
  String encoded_submit = submit_param + "=" + URLEncoder.encode(submit, "UTF-8");

  String encoded = encoded_destination + "&" + encoded_username + "&" + encoded_password + "&" + encoded_submit;

    URL requestUrl = new URL(url);
    HttpURLConnection conn = (HttpURLConnection) requestUrl.openConnection();
    conn.setDoOutput(true);
    conn.setDoInput(true);
    conn.setRequestMethod("POST");

    DataOutputStream osw = new DataOutputStream(conn.getOutputStream());
    osw.writeBytes(encoded);
    osw.flush();

    BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));

    String in = "";

    while ((in = br.readLine()) != null) {
      System.out.println(in);   
    }

    osw.close();
    br.close();

} catch (UnsupportedEncodingException e) {
    e.printStackTrace();
} catch (MalformedURLException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}

以下 html 代码是登录表单。就在表单方法旁边,它显示“action="/login.phtm"”,您会在我的代码中看到我已将其添加到我的 URL 中。这是正确的还是应该只是“ http://www.example.com ”?我都试过了,显然两者都不起作用,所以肯定有其他问题,我假设这是输入。您会看到,对于表单中的每个输入,我都创建了一个 encodeURL 以与我的帖子一起提交,但它似乎不起作用。打印出来的源代码是主网页的源代码,而不是我的帐户的源代码。非常感谢任何帮助,谢谢。

<form method="post" action="/login.phtml">
        <input type="hidden" id="templateLoginDest" name="destination"    value="%2Findex.phtml">
        <table style="width: 350px;" align="center">
            <tr>
                <td valign="top" width="100px"><b>Username:</b></td>
                <td valign="top"><input type="text" name="username" id="templateLoginPopupUsername" size="30"></td>
            </tr>
            <tr>
                <td valign="top"><b>Password:</b></td>
                <td valign="top"><input type="password" name="password" size="30"><br><a href="/account/passwordreset.phtml" style="font-size: 8pt;">Forgot Password?</a><br><br></td>
            </tr>
            <tr>
                <td colspan="2" align="center"><input type="submit" value="Log In!"></td>
            </tr>
        </table>
    </form>
4

0 回答 0