在此示例中,我们将向您展示如何通过标准Java HttpsURLConnection
登录网站。 该技术应可在大多数登录表单中使用。
本示例中使用的工具和Java库
- Google Chrome浏览器–“网络”标签可分析HTTP请求和响应标头字段。
- jsoup库–提取HTML表单值。
- JDK 6。
1.分析Http标头,表单数据。
要登录网站,您需要知道以下值:
- 登录表单URL。
- 登录表单数据。
- 认证的URL。
- Http请求/响应标头。
使用谷歌浏览器获取上述数据。 在Chrome浏览器中,右键单击所有位置,选择“检查元素”->“网络”标签。
在编写代码之前,请尝试通过Chrome登录,观察HTTP请求,响应和表单数据的工作方式,稍后需要在Java中模拟相同的步骤。
2. HttpsURLConnection示例
在此示例中,我们向您展示如何登录Gmail。
总结:
- 将HTTP“ GET”请求发送到Google登录表单– https://accounts.google.com/ServiceLoginAuth
- 通过Google Chrome浏览器的“网络”功能分析表单数据。 或者,您可以查看HTML源代码。
- 使用jSoup库提取所有可见和隐藏表单的数据,并用您的用户名和密码替换。
- 将HTTP“ POST”请求以及构造的参数发送回登录表单
- 用户身份验证后,将另一个HTTP“ GET”请求发送到Gmail页面。 https://mail.google.com/mail/
注意
该示例只是向您展示Java HttpURLConnection的功能。 通常,您应该使用Google Gmail API与Gmail进行交互。
HttpUrlConnectionExample.java
package com.mkyong;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.CookieHandler;
import java.net.CookieManager;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import javax.net.ssl.HttpsURLConnection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
public class HttpUrlConnectionExample {
private List<String> cookies;
private HttpsURLConnection conn;
private final String USER_AGENT = "Mozilla/5.0";
public static void main(String[] args) throws Exception {
String url = "https://accounts.google.com/ServiceLoginAuth";
String gmail = "https://mail.google.com/mail/";
HttpUrlConnectionExample http = new HttpUrlConnectionExample();
// make sure cookies is turn on
CookieHandler.setDefault(new CookieManager());
// 1. Send a "GET" request, so that you can extract the form's data.
String page = http.GetPageContent(url);
String postParams = http.getFormParams(page, "username@gmail.com", "password");
// 2. Construct above post's content and then send a POST request for
// authentication
http.sendPost(url, postParams);
// 3. success then go to gmail.
String result = http.GetPageContent(gmail);
System.out.println(result);
}
private void sendPost(String url, String postParams) throws Exception {
URL obj = new URL(url);
conn = (HttpsURLConnection) obj.openConnection();
// Acts like a browser
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Host", "accounts.google.com");
conn.setRequestProperty("User-Agent", USER_AGENT);
conn.setRequestProperty("Accept",
"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
conn.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
for (String cookie : this.cookies) {
conn.addRequestProperty("Cookie", cookie.split(";", 1)[0]);
}
conn.setRequestProperty("Connection", "keep-alive");
conn.setRequestProperty("Referer", "https://accounts.google.com/ServiceLoginAuth");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", Integer.toString(postParams.length()));
conn.setDoOutput(true);
conn.setDoInput(true);
// Send post request
DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
wr.writeBytes(postParams);
wr.flush();
wr.close();
int responseCode = conn.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + postParams);
System.out.println("Response Code : " + responseCode);
BufferedReader in =
new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// System.out.println(response.toString());
}
private String GetPageContent(String url) throws Exception {
URL obj = new URL(url);
conn = (HttpsURLConnection) obj.openConnection();
// default is GET
conn.setRequestMethod("GET");
conn.setUseCaches(false);
// act like a browser
conn.setRequestProperty("User-Agent", USER_AGENT);
conn.setRequestProperty("Accept",
"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
conn.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
if (cookies != null) {
for (String cookie : this.cookies) {
conn.addRequestProperty("Cookie", cookie.split(";", 1)[0]);
}
}
int responseCode = conn.getResponseCode();
System.out.println("\nSending 'GET' request to URL : " + url);
System.out.println("Response Code : " + responseCode);
BufferedReader in =
new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// Get the response cookies
setCookies(conn.getHeaderFields().get("Set-Cookie"));
return response.toString();
}
public String getFormParams(String html, String username, String password)
throws UnsupportedEncodingException {
System.out.println("Extracting form's data...");
Document doc = Jsoup.parse(html);
// Google form id
Element loginform = doc.getElementById("gaia_loginform");
Elements inputElements = loginform.getElementsByTag("input");
List<String> paramList = new ArrayList<String>();
for (Element inputElement : inputElements) {
String key = inputElement.attr("name");
String value = inputElement.attr("value");
if (key.equals("Email"))
value = username;
else if (key.equals("Passwd"))
value = password;
paramList.add(key + "=" + URLEncoder.encode(value, "UTF-8"));
}
// build parameters list
StringBuilder result = new StringBuilder();
for (String param : paramList) {
if (result.length() == 0) {
result.append(param);
} else {
result.append("&" + param);
}
}
return result.toString();
}
public List<String> getCookies() {
return cookies;
}
public void setCookies(List<String> cookies) {
this.cookies = cookies;
}
}
输出量
Sending 'GET' request to URL : https://accounts.google.com/ServiceLoginAuth
Response Code : 200
Extracting form data...
Sending 'POST' request to URL : https://accounts.google.com/ServiceLoginAuth
Post parameters : dsh=-293322094146108856&GALX=CExqdUbvEr4&timeStmp=&secTok=&_utf8=%E2%98%83
&bgresponse=js_disabled&Email=username&Passwd=password&signIn=Sign+in&PersistentCookie=yes&rmShown=1
Response Code : 200
Sending 'GET' request to URL : https://mail.google.com/mail/
Response Code : 200
<!-- gmail page content.....-->
注意
请参考此等效示例,但使用Apache HttpClient发送HTTP request 。
参考文献
翻译自: https://mkyong.com/java/how-to-automate-login-a-website-java-example/