Я пытаюсь автоматизировать вход в систему с помощью java и использовал этот пример: http://www.mkyong.com/java/how-to-automate-login-a-website-java-example/, чтобы помочь мне сделать это с другим веб-сайтом. Код ниже, как и вывод. У меня вопрос, что означает ошибка и как ее исправить?

public class testing {

  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://www.studentinvestor.org/secure/login.php?dest=http://www.studentinvestor.org/stock-list.php";
String companies = "http://www.studentinvestor.org/stock-list.php";

testing http = new testing();

// 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", ",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(companies);
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", "www.studentinvestor.org");
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-GB,en-US;q=0.8,en;q=0.6");
for (String cookie : this.cookies) {
    conn.addRequestProperty("Cookie", cookie.split(";", 1)[0]);
}
conn.setRequestProperty("Connection", "keep-alive");
conn.setRequestProperty("Content-Type", "text/html");


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,image/webp,*/*;q=0.8");
conn.setRequestProperty("Accept-Language", "en-GB,en-US;q=0.8,en;q=0.6");
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("loginsubmitted");
Elements inputElements = loginform.getElementsByTag("label");
List<String> paramList = new ArrayList<String>();
for (Element inputElement : inputElements) {
    String key = inputElement.attr("name");
    String value = inputElement.attr("value");

    if (key.equals("team-name"))
        value = username;
    else if (key.equals("team-password"))
        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://www.studentinvestor.org/secure/login.php?    dest=http://www.studentinvestor.org/stock-list.php
Response Code : 200
Extracting form's data...

Sending 'POST' request to URL : https://www.studentinvestor.org/secure/login.php?   dest=http://www.studentinvestor.org/stock-list.php
Post parameters : 
Response Code : 200
Exception in thread "main" java.lang.ClassCastException:    sun.net.www.protocol.http.HttpURLConnection cannot be cast to   javax.net.ssl.HttpsURLConnection
    at testing.GetPageContent(testing.java:98)
  at testing.main(testing.java:44)

Поэтому сообщение об ошибке:

Exception in thread "main" java.lang.ClassCastException:    sun.net.www.protocol.http.HttpURLConnection cannot be cast to   javax.net.ssl.HttpsURLConnection
        at testing.GetPageContent(testing.java:98)
      at testing.main(testing.java:44)
-1
Thomas Smith 4 Ноя 2014 в 20:08
Какую часть скопированного кода вы понимаете? Вы понимаете, что такое кастинг, и что происходит в строке 44?
 – 
Jon Skeet
4 Ноя 2014 в 20:12
Какая строка является строкой 98 тестирования?
 – 
Sam I am says Reinstate Monica
4 Ноя 2014 в 20:12
Строка 44 — String result = http.GetPageContent(companies);, строка 98 — conn = (HttpsURLConnection) obj.openConnection();. Боюсь, я немного нуб, и поэтому не понимаю ничего, кроме самых основ, поэтому я был бы признателен, если бы вы объяснили мне, что такое кастинг.
 – 
Thomas Smith
4 Ноя 2014 в 20:13
Быстрый поиск говорит о преобразовании переменной из одного типа в другой, так ли это?
 – 
Thomas Smith
4 Ноя 2014 в 20:14
Кастинг — это когда вы берете объект одного типа и указываете компилятору обрабатывать его как другой тип.
 – 
Sam I am says Reinstate Monica
4 Ноя 2014 в 20:14

2 ответа

Глупый я! Если вы получили эту ошибку, убедитесь, что ваши URL-адреса являются HTTPS, а не просто http или www!

0
Thomas Smith 4 Ноя 2014 в 20:53

Посмотрите на исключение: sun.net.www.protocol.http.HttpURLConnection нельзя преобразовать в javax.net.ssl.HttpsURLConnection.

Здесь протокол требуемого URL-адреса должен быть Https вместо HTTP.

Поэтому использование приведенного ниже кода решит вашу проблему:

Строковые компании = "https://www.studentinvestor.org/stock-list.php ";

0
4 Ноя 2014 в 21:18