测试服务器是否在 Java 中启动的正确方法?

Proper way to test if server is up in Java?(测试服务器是否在 Java 中启动的正确方法?)

本文介绍了测试服务器是否在 Java 中启动的正确方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

简单地查看是否可以建立与网站/服务器的连接的正确方法是什么?我想要一个我正在编码的应用程序,如果我的网站离线,它会提醒我.

What would be the proper way to simply see if a connection to a website/server can be made? I want this for an application I am coding that will just alert me if my website goes offline.

谢谢!

推荐答案

您可以使用 HttpURLConnection 发送请求并检查响应正文中是否有该页面唯一的文本(而不仅仅是检查是否有响应以防万一出现错误或维护页面或其他内容).

You can use an HttpURLConnection to send a request and check the response body for text that is unique to that page (rather than just checking to see if there's a response at all, just in case an error or maintenance page or something is being served).

Apache Commons 有一个库,可以删除很多制作模板Java 中的 Http 请求.

Apache Commons has a library that removes a lot of the boiler plate of making Http requests in Java.

我从来没有专门在 Android 上做过类似的事情,但如果有什么不同,我会感到惊讶.

I've never done anything like this specifically on Android, but I'd be surprised if it's any different.

这是一个简单的例子:

URL url = new URL(URL_TO_APPLICATION);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
InputStream stream = connection.getInputStream();
Scanner scanner = new Scanner(stream); // You can read the stream however you want. Scanner was just an easy example
boolean found = false;
while(scanner.hasNext()) {
    String next = scanner.next();
    if(TOKEN.equals(next)) {
        found = true;
        break;
    }
}

if(found) {
    doSomethingAwesome();
} else {
    throw aFit();
}

这篇关于测试服务器是否在 Java 中启动的正确方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:测试服务器是否在 Java 中启动的正确方法?

基础教程推荐