我想用用户名和密码登录到https网站,转到该网站的一个url并在url下载页面(或者解析该页面的内容)。我只想使用核心Java,而不使用htmlunit、jsoup等。我有下面的代码来学习如何做到这一点,但它并没有向我展示如何登录到一个网站。请告诉我如何登录,维护一个会话,然后最后关闭连接。
源- http://www.mkyong.com/java/java-https-client-httpsurlconnection-example/
import java.net.MalformedURLException;
import java.net.URL;
import java.security.cert.Certificate;
import java.io.*;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLPeerUnverifiedException;
public class HttpsClient{
public static void main(String[] args)
{
new HttpsClient().testIt();
}
private void testIt(){
String https_url = "https://www.google.com/";
URL url;
try {
url = new URL(https_url);
HttpsURLConnection con = (HttpsURLConnection)url.openConnection();
//dumpl all cert info
print_https_cert(con);
//dump all the content
print_content(con);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private void print_https_cert(HttpsURLConnection con){
if(con!=null){
try {
System.out.println("Response Code : " + con.getResponseCode());
System.out.println("Cipher Suite : " + con.getCipherSuite());
System.out.println("\n");
Certificate[] certs = con.getServerCertificates();
for(Certificate cert : certs){
System.out.println("Cert Type : " + cert.getType());
System.out.println("Cert Hash Code : " + cert.hashCode());
System.out.println("Cert Public Key Algorithm : "
+ cert.getPublicKey().getAlgorithm());
System.out.println("Cert Public Key Format : "
+ cert.getPublicKey().getFormat());
System.out.println("\n");
}
} catch (SSLPeerUnverifiedException e) {
e.printStackTrace();
} catch (IOException e){
e.printStackTrace();
}
}
}
private void print_content(HttpsURLConnection con){
if(con!=null){
try {
System.out.println("****** Content of the URL ********");
BufferedReader br =
new BufferedReader(
new InputStreamReader(con.getInputStream()));
String input;
while ((input = br.readLine()) != null){
System.out.println(input);
}
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}发布于 2014-12-07 06:34:14
每个网站都以不同的方式管理登录。您将需要搜索网站,找出会话是如何维护的,并以服务器无法判断它不是浏览器的方式来模拟这些功能。
通常,web服务器将秘密散列存储在cookie中。这是一个过程
以上所有这些都只能使用URL和HttpsURLConnection来完成,但是您需要准确地模仿浏览器来欺骗服务器。
对于侦察,我建议使用像费德勒这样的工具。它捕获了来自see服务器和后台的所有通信,这样您就可以准确地看到在http级别上发生了什么来模仿您的java代码。
这里是小提琴的概述。我从来没看过原木。Fiddler有一个甜美的界面。这段视频真的很无聊,但它给出了界面的概述。您想要查看原始文本视图,并模仿它。
对于另一个问题,owasp是最佳实践的一个很好的资源。现实情况是,有很多不安全和糟糕的代码,它们做的事情是你从来没有想到过的。我见过一台服务器将布尔值放入脚本标记中作为javascript变量存储。您只需仔细观察服务器在登录后如何更改响应。对于遵循最佳实践的流行网站,他们将使用上述方法。
https://stackoverflow.com/questions/27340211
复制相似问题