我想登录一个网站,但如果我尝试使用以下代码: 包网址;
//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 来获取登录信息?
感谢所有建议。
最佳答案
您可以调用URL
对象的openConnection
方法来获取URLConnection
对象。您可以使用此 URLConnection
对象来设置连接之前可能需要的参数和常规请求属性。仅当调用 URLConnection.connect
方法时,才会启动与 URL
表示的远程对象的连接。以下代码打开与网站 example.com 的连接:
try {
URL myURL = new URL("http://login.szn.cz");
URLConnection myURLConnection = myURL.openConnection();
myURLConnection.connect();
}
catch (MalformedURLException e) {
// new URL() failed
// ...
}
catch (IOException e) {
// openConnection() failed
// ...
}
每次调用此 URL
协议(protocol)处理程序的 openConnection
方法都会创建一个新的 URLConnection
对象。
另请参阅这些链接..
关于java - 登录网站 (Java),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15819030/