简体   繁体   中英

How to determine the web service status using HttpURLConnection?

I am posting a Message to a Rest WEB Service using standars java.net package . This is the way i was contacting the web service and posting my request to it .

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

There are a lot of Socket examples and I hope this approach helps you with your problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM