从URL HTTP请求java列表中获取活动URL

时间:2017-04-04 04:59:43

标签: java httprequest

private URL getActiveUrl(HttpRequest httpRequest) throws Exception {
    if (urlList.size() > 0) {
        for (String url : urlList) {
            URL serverUrl = new URL(url);
            HttpURLConnection connection = null;
            try {
                if (!StringUtil.isNullOrEmpty(url)) {
                    connection = (HttpURLConnection) (useProxy ? serverUrl.openConnection(new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyAddress, proxyPort))) : serverUrl.openConnection());
                    connection.setRequestMethod("HEAD");
                    if(connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                        logger.debug("Connection established with:" + url);
                        return serverUrl;
                    } else if (urlList.indexOf(url) == urlList.size() - 1) {
                        throw new RemoteAccessException();
                    }
                    logger.info("Failed to connect :" + url);
                } else {
                    logger.error("Empty BL sever address");
                    throw new RemoteAccessException();
                }
            } catch (Exception e) {
                if (urlList.indexOf(url) == urlList.size() - 1) {
                    e.printStackTrace();
                    throw new RemoteAccessException();
                } else {
                    logger.info("Failed to connect :" + url);
                    continue;
                }
            } finally {
                if(connection != null) {
                    connection.disconnect();
                }
            }
        }
    } else {
        throw new RemoteAccessException("BL server list is empty");
    }
    return null;
}

以上是我的代码。如果我的第一个URL无法连接,列表中的下一个URL即使可以访问也会失败。我在连接到第二个网址时收到connect in progress exception。如果第一个URL可以访问,那么它就可以连接。

我错过了什么吗?

0 个答案:

没有答案