java 我如何知道我是否已成功连接到我打开连接的 URL?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13775103/
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
How do I know if I have successfully connected to the URL I opened a connection with?
提问by saplingPro
To check if I can connect to the web-app named serviceI open a connection to its address.How do I check if have connected to this URL/Service? I was thinking of sending some sort of status method (as a client tries to open connection to this URL) that determines if the client was able to establish a successful connection to the service. But how do I do that ?
要检查我是否可以连接到名为service的 web 应用程序,我打开了一个到其地址的连接。如何检查是否已连接到此URL/Service?我正在考虑发送某种状态方法(当客户端尝试打开与此 URL 的连接时),以确定客户端是否能够成功建立到服务的连接。但是我该怎么做呢?
I was trying something like this :
我正在尝试这样的事情:
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 ?
回答by Evgeniy Dorofeev
I suggest
我建议
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());
it prints 200
(OK)
它打印200
(确定)