1

我刚刚建立了到本地主机的 url 连接:8080 并使用 JBOSS 服务器检查了 200-209 之间的 http 响应代码。

public class Welcome extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

response.setContentType("text/html");
 PrintWriter pw = response.getWriter();
URL url = new URL("http://localhost:8080");
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("GET");
connection.connect();

int code = connection.getResponseCode();
System.out.println("code=="+code);
if (code>=200 && code <= 209){

       pw.println("<h1>Welcome....</h1>");
       pw.println("<p>Service is accessable</p>");


    }
else 

{System.out.println("service is denied");}
    }}

如果 HTTP 响应代码在 200-209 之外或无法建立连接,则必须执行以下步骤:

1)如果 Jboss Service 正在运行,则重新启动。

2)如果 Jboss Service 没有运行,则启动它。

现在在这里我想知道如何以编程方式知道服务器是否正在运行以执行上述两个步骤..请帮助我..谢谢

4

2 回答 2

2

您应该捕获发生超时(服务器根本没有运行)时上升的 IOException。

像这样的东西:

public class Welcome extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

response.setContentType("text/html");
 PrintWriter pw = response.getWriter();
URL url = new URL("http://localhost:8080");

try {
    HttpURLConnection connection = (HttpURLConnection)url.openConnection();
} catch (IOException ex) {
    // (probably) service is not running 
    // start service
    return;
}

connection.setRequestMethod("GET");
connection.connect();

int code = connection.getResponseCode();
System.out.println("code=="+code);
if (code>=200 && code <= 209){

       pw.println("<h1>Welcome....</h1>");
       pw.println("<p>Service is accessable</p>");


    }
else 

{System.out.println("service is denied");}
    }}
于 2013-04-06T10:38:51.160 回答
1

我认为这是已经讨论过的事情。您需要为此捕获异常。你可能想研究这样的事情

于 2013-04-06T10:44:17.813 回答