我想登錄到一個網站,但如果我嘗試使用此代碼: 程序包URL;登錄網站(Java)
//Variables to hold the URL object and its connection to that URL.
import java.net.*;
import java.io.*;
public class URLLogin {
private static URL URLObj;
private static URLConnection connect;
public static void main(String[] args) {
try {
// Establish a URL and open a connection to it. Set it to output mode.
URLObj = new URL("http://login.szn.cz");
connect = URLObj.openConnection();
connect.setDoOutput(true);
}
catch (MalformedURLException ex) {
System.out.println("The URL specified was unable to be parsed or uses an invalid protocol. Please try again.");
System.exit(1);
}
catch (Exception ex) {
System.out.println("An exception occurred. " + ex.getMessage());
System.exit(1);
}
try {
// Create a buffered writer to the URLConnection's output stream and write our forms parameters.
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(connect.getOutputStream(),"UTF-8"));
writer.write("username=S&password=s&login=Přihlásit se");
writer.close();
// Now establish a buffered reader to read the URLConnection's input stream.
BufferedReader reader = new BufferedReader(new InputStreamReader(connect.getInputStream()));
String lineRead = "";
Read all available lines of data from the URL and print them to screen.
while ((lineRead = reader.readLine()) != null) {
System.out.println(lineRead);
}
reader.close();
}
catch (Exception ex) {
System.out.println("There was an error reading or writing to the URL: " + ex.getMessage());
}
}
}
我得到這個錯誤:
There was an error reading or writing to the URL: Server returned HTTP response code: 405 for URL: http://login.szn.cz
這裏是一個辦法,我怎麼可以登錄到這個網站?或者,也許我可以在Opera瀏覽器中使用cookie和登錄信息?
感謝您的所有建議。
我可以使用HtmlUnit,對於這樣的工作,因爲它不僅支持Cookie,而且JavaScript的。 – MrSmith42 2013-04-04 18:45:25
您嘗試訪問的頁面是一個簡單的HTML頁面 - 您應該使用https://login.szn.cz/loginProcess代替。另外,您需要使用SSL連接。此外,您需要將請求方法指定爲POST,將Content-Type指定爲「application/x-www-form-urlencoded」。此外,您還需要對要寫入請求正文的數據進行編碼。此外,您似乎缺少一些參數(至少與使用主HTML頁面登錄時相比)。您可能需要HtmlUnit,正如@ MrSmith42所建議的那樣。 – Perception 2013-04-04 18:55:22
您可以嘗試將'connect'連接到'HttpURLConnection',然後使用'setRequestMethod(「POST」)將請求方法設置爲POST;' – srkavin 2013-04-04 18:56:21