[英]How to determine the web service status using HttpURLConnection?
I am posting a Message to a Rest WEB Service using standars java.net package . 我正在使用standars java.net包将消息发布到Rest WEB服务。 This is the way i was contacting the web service and posting my request to it .
这就是我联系Web服务并将其请求发布到它的方式。
package com;
import java.io.IOException;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class NetClientPost {
public static void main(String[] args) {
HttpURLConnection conn = null;
OutputStream os = null;
try {
URL url = new URL("http://localhost:8080/RestTest/ajax/user_info");
conn = (HttpURLConnection) url.openConnection();
// System.out.println(conn.getResponseCode());
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
String input = "{\"qty\":100,\"name\":\"sdsfds 4\"}";
os = conn.getOutputStream();
os.write(input.getBytes());
os.flush();
conn.getInputStream();
}
catch (Exception e) {
e.printStackTrace();
}
finally {
try {
os.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
conn.disconnect();
}
}
}
my concern is that if the service is up and running only , i want to post the request to it or else not . 我担心的是,如果该服务仅启动并正在运行,我想将请求发布到该服务上,否则就不发布该请求。
Please tell me if that is possible to check or not ?? 请告诉我是否可以检查?
thanks in advance . 提前致谢 。
You can try to establish a socket connection to the host. 您可以尝试建立与主机的套接字连接。 If the socket is running well your request should work.
如果套接字运行良好,则您的请求应该可以正常工作。
Just a really short example: 只是一个很简短的例子:
Socket client;
try{
client = new Socket("localhost", 8080);
// Do your stuff
} catch(Exception e) {
System.out.println("Error");
}
Documentation: https://developer.android.com/reference/java/net/Socket.html 文档: https : //developer.android.com/reference/java/net/Socket.html
There are a lot of Socket examples and I hope this approach helps you with your problem. 有很多Socket示例,我希望这种方法可以帮助您解决问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.