2012-12-08 26 views
1

要檢查我是否可以連接到名爲的服務我打開了一個到它的地址的連接。如何檢查是否已連接到此網址/服務?我正在考慮發送某種狀態方法(如客戶端試圖打開與此URL的連接),以確定客戶端是否能夠建立與服務的成功連接。但我該怎麼做?如何知道我是否已成功連接到與我打開連接的URL?

我是想這樣的事情:

  final URL url = new URL("http://localhost:8084/service/index.jsp"); 
      final URLConnection urlc = url.openConnection(); 
      InputStream response = urlc.getInputStream(); 
      // Now call a method in the service app that sends a status method... 
      // .....or can I get away with this ? 
+1

如何使用url.getResponseCode()== OK(200)檢查網絡應用程序是否返回OK狀態? – Waqas

+0

@Waqas是什麼方法?我相信它不是預定義的方法..? – saplingPro

+0

它在HttpUrlConnection類中:http://docs.oracle.com/javase/1.4.2/docs/api/java/net/HttpURLConnection.html – Waqas

回答

4

我建議

URL url = new URL("http://stackoverflow.com/questions/13775103/how-do-i-know-if-i-have-successfully-connected-to-the-url-i-opened-a-connection"); 
    HttpURLConnection conn = (HttpURLConnection)url.openConnection(); 
    System.out.println(conn.getResponseCode()); 

它打印200(OK)

相關問題