我正在尝试查看其中一个网页的httpurlconnection

时间:2018-03-13 18:25:31

标签: java selenium selenium-webdriver httpurlconnection

在尝试检查其中一个网页的selenium中的断开链接时,我无法获得响应消息。我得到以下错误。

你能帮我解决一下这个问题吗? 使用的代码是:

HttpURLConnection connection = (HttpURLConnection) new URL(activelinks.get(j).getAttribute("href")).openConnection();
connection.connect();
Serializable response = connection.getResponseMessage();
connection.disconnect();
System.out.println(activelinks.get(j).getAttribute("href")+"----->"+response);

错误是:

Exception in thread "main" java.net.ProtocolException: Server redirected too many  times (20)
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(Unknown Source)
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
    at java.net.HttpURLConnection.getResponseCode(Unknown Source)
    at java.net.HttpURLConnection.getResponseMessage(Unknown Source)
    at sun.net.www.protocol.https.HttpsURLConnectionImpl.getResponseMessage(Unknown Source)
    at Testng.amazonn.amazontestcase.main(amazontestcase.java:45)

1 个答案:

答案 0 :(得分:0)

如果您要提取响应,可能需要设置明确的连接超时,并在关闭连接之前检查if()循环中的响应,如下所示:

HttpURLConnection connection = (HttpURLConnection) new URL(activelinks.get(j).getAttribute("href")).openConnection();
connection.setConnectTimeout(5000);
connection.connect();
if (connection.getResponseCode() == 200) 
{
    System.out.println(activelinks.get(j).getAttribute("href")+"----->" + connection.getResponseMessage());
}

if (connection.getResponseCode() == httpUrlConnect.HTTP_NOT_FOUND) 
{
    System.out.println(activelinks.get(j).getAttribute("href")+"----->" + connection.HTTP_NOT_FOUND);
}