import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
/**
* Created by Kevin on 26/01/14.
*/
public final class Boot {
public Boot(final String... args) {
try {
final URL url = new URL(args[0]);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.addRequestProperty("Host", "http://example.com/");
connection.addRequestProperty("Protocol", "HTTP/1.1");
connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.3; WOW64; rv:26.0) Gecko/20100101 Firefox/26.0");
connection.addRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
connection.addRequestProperty("Referer", "http://example.com/");
connection.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
connection.addRequestProperty("Cookie", "__cfduid=d2f9cfb1c350013cc71a12eaedc660a551390762958146; __utma=241386960.1917361281.1390762966.1390762966.1390762966.1; __utmb=241386960.1.10.1390762966; __utmc=241386960; __utmz=241386960.1390762966.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none)");
String encodedParams = URLEncoder.encode("login=true&email=kevin@example.com&pwd=mypassword");
OutputStream wr = connection.getOutputStream();
wr.write(encodedParams.getBytes());
wr.flush();
wr.close();
final InputStreamReader isr = new InputStreamReader(connection.getInputStream(), "UTF-8");
final BufferedReader br = new BufferedReader(isr);
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
System.out.println("Response code: " + connection.getResponseCode());
System.out.println(encodedParams);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(final String... args) {
new Boot("https://www.example.com/admin/index.php");
}
}
正如您在此处看到的代码,我正在尝试为网站的管理面板创建POST请求。但是,我想让它登录,所以打印出“管理仪表板”。
我一直在努力尝试超过2个小时而且我无法做到。尽管如此,这可能与Java有关吗?
答案 0 :(得分:0)
当我在crosspost发布时,您可以使用HtmlUnit来避免编写所有代码。 getting started guide显示了登录的示例。
由于URL在参数中,因此您现在看起来像GET请求。
String encodedParams = URLEncoder.encode("login=true&email=kevin@example.com&pwd=mypassword");
或者,您可以尝试Apache Http Components库。