このコードを機能させようとして、Web サイトに投稿を送信してログインできるようにしました。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 」であるべきですか? 私は両方を試しましたが、明らかにどちらもうまくいかないようです。何か他のことが間違っているに違いありません。フォームの入力ごとに、投稿と一緒に送信するコード化された URL を作成しましたが、機能していないようです。印刷されるソース コードは、メインの Web ページのものであり、私のアカウントのものではありません。どんな助けでも大歓迎です、ありがとう。
<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>