正确的方式来测试,如果服务器Java是吗? [英] Proper way to test if server is up in Java?

查看:216
本文介绍了正确的方式来测试,如果服务器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的百科全书有一个图书馆,消除了很多使锅炉板HTTP请求在Java中。

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.

下面是一个简单的例子:

Here's a quick example:

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是吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆