登录到网站(Java)
我想登录到一个网站,但如果我用以下代码尝试: 包URL登录到网站(Java),java,login,Java,Login,我想登录到一个网站,但如果我用以下代码尝试: 包URL //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
//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());
}
}
}
我得到这个错误:
读取或写入URL时出错:服务器返回HTTP
URL的响应代码:405:
这是我登录这个网站的方法吗?或者我可以在Opera浏览器中使用带有登录信息的cookies
感谢所有建议。您可以调用
URL
对象的openConnection
方法来获取URLConnection
对象。您可以使用此URLConnection
对象设置连接前可能需要的参数和常规请求属性。只有在调用URLConnection.connect
方法时,才会启动到URL
表示的远程对象的连接。以下代码打开到网站example.com的连接:
每次通过为此URL
调用协议处理程序的openConnection
方法,都会创建一个新的URLConnection
对象
也可以查看这些链接
connect
转换为HttpURLConnection
,然后使用setRequestMethod(“POST”)将请求方法设置为POST代码>@MrSmith42我下载了htmlUnit,看起来很棒。有了这个,我可以登录到我的网站,这是一个更优雅的解决方案。谢谢男士:)我使用了史密斯先生42号的建议表,但是谢谢你的回复:)
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
// ...
}