How To Automate Login A Website – Java Example

向右看齐 2022-08-24 11:14 223阅读 0赞

In this example, we will show you how to login a website via standard Java HttpsURLConnection. This technique should be working in most of the login form.

Tools & Java Library used in this example

  1. Google Chrome Browser – Network tab to analyze HTTP request and response header fields.
  2. jsoup library – Extracts HTML form values.
  3. JDK 6.

1. Analyze Http Headers, form data.

To login a website, you need to know following values :

  1. Login form URL.
  2. Login form data.
  3. URL for authentication.
  4. Http request / response header.

Uses Google Chrome to get above data. In Chrome, right click everywhere, choose “Inspect Element” -> “Network” tab.

chrome-network

Before you code, try login via Chrome, observe how the HTTP request, response and form data works, later you need to simulate the same steps in Java.

2. HttpsURLConnection Example

In this example, we show you how to login Gmail.

Summary :

  1. Send an HTTP “GET” request to Google login form – https://accounts.google.com/ServiceLoginAuth
  2. Analyze the form data via Google Chrome’s “Network” feature. Alternatively, you can view the HTML source code.
  3. Use jSoup library to extract all visible and hidden form’s data, replace with your username and password.
  4. Send a HTTP “POST” request back to login form, along with the constructed parameters
  5. After user authenticated, send another HTTP “GET” request to Gmail page. https://mail.google.com/mail/

Note
This example is just to show you the capability and functionality of Java HttpURLConnection. In general, you should use the Google Gmail API to interact with Gmail.

HttpUrlConnectionExample.java

  1. package com.mkyong;
  2. import java.io.BufferedReader;
  3. import java.io.DataOutputStream;
  4. import java.io.InputStreamReader;
  5. import java.io.UnsupportedEncodingException;
  6. import java.net.CookieHandler;
  7. import java.net.CookieManager;
  8. import java.net.URL;
  9. import java.net.URLEncoder;
  10. import java.util.ArrayList;
  11. import java.util.List;
  12. import javax.net.ssl.HttpsURLConnection;
  13. import org.jsoup.Jsoup;
  14. import org.jsoup.nodes.Document;
  15. import org.jsoup.nodes.Element;
  16. import org.jsoup.select.Elements;
  17. public class HttpUrlConnectionExample {
  18. private List<String> cookies;
  19. private HttpsURLConnection conn;
  20. private final String USER_AGENT = "Mozilla/5.0";
  21. public static void main(String[] args) throws Exception {
  22. String url = "https://accounts.google.com/ServiceLoginAuth";
  23. String gmail = "https://mail.google.com/mail/";
  24. HttpUrlConnectionExample http = new HttpUrlConnectionExample();
  25. // make sure cookies is turn on
  26. CookieHandler.setDefault(new CookieManager());
  27. // 1. Send a "GET" request, so that you can extract the form's data.
  28. String page = http.GetPageContent(url);
  29. String postParams = http.getFormParams(page, "username@gmail.com", "password");
  30. // 2. Construct above post's content and then send a POST request for
  31. // authentication
  32. http.sendPost(url, postParams);
  33. // 3. success then go to gmail.
  34. String result = http.GetPageContent(gmail);
  35. System.out.println(result);
  36. }
  37. private void sendPost(String url, String postParams) throws Exception {
  38. URL obj = new URL(url);
  39. conn = (HttpsURLConnection) obj.openConnection();
  40. // Acts like a browser
  41. conn.setUseCaches(false);
  42. conn.setRequestMethod("POST");
  43. conn.setRequestProperty("Host", "accounts.google.com");
  44. conn.setRequestProperty("User-Agent", USER_AGENT);
  45. conn.setRequestProperty("Accept",
  46. "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
  47. conn.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
  48. for (String cookie : this.cookies) {
  49. conn.addRequestProperty("Cookie", cookie.split(";", 1)[0]);
  50. }
  51. conn.setRequestProperty("Connection", "keep-alive");
  52. conn.setRequestProperty("Referer", "https://accounts.google.com/ServiceLoginAuth");
  53. conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
  54. conn.setRequestProperty("Content-Length", Integer.toString(postParams.length()));
  55. conn.setDoOutput(true);
  56. conn.setDoInput(true);
  57. // Send post request
  58. DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
  59. wr.writeBytes(postParams);
  60. wr.flush();
  61. wr.close();
  62. int responseCode = conn.getResponseCode();
  63. System.out.println("\nSending 'POST' request to URL : " + url);
  64. System.out.println("Post parameters : " + postParams);
  65. System.out.println("Response Code : " + responseCode);
  66. BufferedReader in =
  67. new BufferedReader(new InputStreamReader(conn.getInputStream()));
  68. String inputLine;
  69. StringBuffer response = new StringBuffer();
  70. while ((inputLine = in.readLine()) != null) {
  71. response.append(inputLine);
  72. }
  73. in.close();
  74. // System.out.println(response.toString());
  75. }
  76. private String GetPageContent(String url) throws Exception {
  77. URL obj = new URL(url);
  78. conn = (HttpsURLConnection) obj.openConnection();
  79. // default is GET
  80. conn.setRequestMethod("GET");
  81. conn.setUseCaches(false);
  82. // act like a browser
  83. conn.setRequestProperty("User-Agent", USER_AGENT);
  84. conn.setRequestProperty("Accept",
  85. "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
  86. conn.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
  87. if (cookies != null) {
  88. for (String cookie : this.cookies) {
  89. conn.addRequestProperty("Cookie", cookie.split(";", 1)[0]);
  90. }
  91. }
  92. int responseCode = conn.getResponseCode();
  93. System.out.println("\nSending 'GET' request to URL : " + url);
  94. System.out.println("Response Code : " + responseCode);
  95. BufferedReader in =
  96. new BufferedReader(new InputStreamReader(conn.getInputStream()));
  97. String inputLine;
  98. StringBuffer response = new StringBuffer();
  99. while ((inputLine = in.readLine()) != null) {
  100. response.append(inputLine);
  101. }
  102. in.close();
  103. // Get the response cookies
  104. setCookies(conn.getHeaderFields().get("Set-Cookie"));
  105. return response.toString();
  106. }
  107. public String getFormParams(String html, String username, String password)
  108. throws UnsupportedEncodingException {
  109. System.out.println("Extracting form's data...");
  110. Document doc = Jsoup.parse(html);
  111. // Google form id
  112. Element loginform = doc.getElementById("gaia_loginform");
  113. Elements inputElements = loginform.getElementsByTag("input");
  114. List<String> paramList = new ArrayList<String>();
  115. for (Element inputElement : inputElements) {
  116. String key = inputElement.attr("name");
  117. String value = inputElement.attr("value");
  118. if (key.equals("Email"))
  119. value = username;
  120. else if (key.equals("Passwd"))
  121. value = password;
  122. paramList.add(key + "=" + URLEncoder.encode(value, "UTF-8"));
  123. }
  124. // build parameters list
  125. StringBuilder result = new StringBuilder();
  126. for (String param : paramList) {
  127. if (result.length() == 0) {
  128. result.append(param);
  129. } else {
  130. result.append("&" + param);
  131. }
  132. }
  133. return result.toString();
  134. }
  135. public List<String> getCookies() {
  136. return cookies;
  137. }
  138. public void setCookies(List<String> cookies) {
  139. this.cookies = cookies;
  140. }
  141. }

Output

  1. Sending 'GET' request to URL : https://accounts.google.com/ServiceLoginAuth
  2. Response Code : 200
  3. Extracting form data...
  4. Sending 'POST' request to URL : https://accounts.google.com/ServiceLoginAuth
  5. Post parameters : dsh=-293322094146108856&GALX=CExqdUbvEr4&timeStmp=&secTok=&_utf8=%E2%98%83
  6. &bgresponse=js_disabled&Email=username&Passwd=password&signIn=Sign+in&PersistentCookie=yes&rmShown=1
  7. Response Code : 200
  8. Sending 'GET' request to URL : https://mail.google.com/mail/
  9. Response Code : 200
  10. <!-- gmail page content.....-->

Note
Refer to this equivalent example, but using Apache HttpClient to send HTTP request.

References

  1. Automated Login To a Website
  2. Android documentation – HttpURLConnection
  3. Sending HTTP Request GET/POST to form with Java?
  4. jSoup library
  5. Apache HttpClient examples

发表评论

表情:
评论列表 (有 0 条评论,223人围观)

还没有评论,来说两句吧...

相关阅读