Java 如何以编程方式测试 HTTP 连接?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/285860/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 12:33:39  来源:igfitidea点击:

How can I programmatically test an HTTP connection?

javahttpurlhttpconnection

提问by brasskazoo

Using Java, how can I test that a URL is contactable, and returns a valid response?

使用 Java,如何测试 URL 是否可联系并返回有效响应?

http://stackoverflow.com/about

采纳答案by brasskazoo

The solution as a unit test:

作为单元测试的解决方案:

public void testURL() throws Exception {
    String strUrl = "http://stackoverflow.com/about";

    try {
        URL url = new URL(strUrl);
        HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
        urlConn.connect();

        assertEquals(HttpURLConnection.HTTP_OK, urlConn.getResponseCode());
    } catch (IOException e) {
        System.err.println("Error creating HTTP connection");
        e.printStackTrace();
        throw e;
    }
}

回答by John T

Since java 5 if i recall, the InetAdress class contains a method called isReachable(); so you can use it to make a ping implementation in java. You can also specify a timeout for this method. This is just another alternative to the unit test method posted above, which is probably more efficient.

我记得从 java 5 开始,InetAdress 类包含一个名为 isReachable(); 的方法。所以你可以用它在java中进行ping实现。您还可以为此方法指定超时。这只是上面发布的单元测试方法的另一种替代方法,它可能更有效。

回答by Charif

import org.apache.commons.validator.UrlValidator;

public class ValidateUrlExample {

    public static void main(String[] args) {

        UrlValidator urlValidator = new UrlValidator();

        //valid URL
        if (urlValidator.isValid("http://www.mkyong.com")) {
            System.out.println("url is valid");
        } else {
            System.out.println("url is invalid");
        }

        //invalid URL
        if (urlValidator.isValid("http://invalidURL^$&%$&^")) {
            System.out.println("url is valid");
        } else {
            System.out.println("url is invalid");
        }
    }
}

Output:

输出:

url is valid
url is invalid

source : http://www.mkyong.com/java/how-to-validate-url-in-java/

来源:http: //www.mkyong.com/java/how-to-validate-url-in-java/

回答by Sam Ginrich

System.out.println(new InetSocketAddress("http://stackoverflow.com/about", 80).isUnresolved());

delivers falseif page is reachable, which is a precondition.

如果页面可访问,则传递false,这是前提条件。

In order to cover initial question completely, you need to implement a http getor post.

为了完全涵盖最初的问题,您需要实现http getpost