爪哇太阳报。网www.protocol。https。无法将HttpsURLConnectionImpl强制转换为sun。网www.protocol。http。可设定代理
我使用selenium库进行测试。但是下面的代码给了我类强制转换异常。我在谷歌上搜索了这个异常,但没有找到解决方案。我对Https连接和http连接感到困惑。帮我解决这个异常。多谢各位
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import sun.net.www.protocol.http.HttpURLConnection;
public class TestMakeMySushi {
private static final String HttpURLConnection = null;
public static void main(String[] args) throws InterruptedException, MalformedURLException, IOException {
System.setProperty("webdriver.chrome.driver", "C:\\Users\\Dev-24\\Downloads\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.manage().deleteAllCookies();
driver.manage().timeouts().pageLoadTimeout(30, TimeUnit.SECONDS);
driver.manage().timeouts().implicitlyWait(40, TimeUnit.SECONDS);
driver.get("https://www.makemysushi.com/404?");
List<WebElement> linklist = driver.findElements(By.tagName("a"));
linklist.addAll(driver.findElements(By.tagName("img")));
System.out.println("size of all link and images list" + linklist.size());
List<WebElement> activelist = new ArrayList<WebElement>();
for (int i = 0; i < linklist.size(); i++) {
System.out.println(linklist.get(i).getAttribute("href"));
if (linklist.get(i).getAttribute("href") != null && (!linklist.get(i).getAttribute("href").contains("javascript"))) {
activelist.add(linklist.get(i));
}
}
System.out.println("size of activelink list" + activelist.size());
for (int j = 0; j < activelist.size(); j++) {
HttpURLConnection connection = (HttpURLConnection) new URL(activelist.get(j).getAttribute("href")).openConnection();
connection.connect();
String response = connection.getResponseMessage();
connection.disconnect();
System.out.println(activelist.get(j).getAttribute("href") + "----" + response);
}
}
}
我面临的例外
Exception in thread "main" java.lang.ClassCastException: sun.net.www.protocol.https.HttpsURLConnectionImpl cannot be cast to sun.net.www.protocol.http.HttpURLConnection
at TestMakeMySushi.main(TestMakeMySushi.java:76)
C:\Users\Dev-24\AppData\Local\NetBeans\Cache\8.1\executor-snippets\run.xml:53: Java returned: 1
# 1 楼答案
将
HttpURLConnection
类的导入语句从import sun.net.www.protocol.http.HttpURLConnection;
更改为import java.net.HttpURLConnection;
您不应该在应用程序代码中使用
sun
包和类。它们是JVM内部的# 2 楼答案
我也面临同样的问题,因为我
导入com。太阳网ssl。HttpsURLConnection
移除并在下面导入
导入javax。网ssl。HttpsURLConnection
# 3 楼答案
@KarolDowbecki的分析是正确的
HttpURLConnection应通过以下方式解决,而不是
sun.net.www.protocol.http.HttpURLConnection;
HttpURLConnection:我能够执行您的程序,该程序产生以下输出:
理由
列表活动列表包含一个元素:
当您试图通过href属性mailto建立连接时:info@makemysushi.com例如:
无法建立成功的连接,因为无法将MailToURLConnection对象强制转换为HttpURLConnection对象并引发java。lang.ClassCastException