Java: Executing HTTP REST GET call without reading the response

Francesco Marchioni :


I'm in a scenario where I'm sending an HTTP GET towards a JVM Server. The purpose of this HTTP GET is to stop the remote JVM (which will restart automatically as it's in Kubernetes Pod).

What I have observed is that, when sending the request with cURL it works as expected:

$ curl namespace.192.168.42.204.nip.io/rest

However, when sending the HTTP GET in Java it fails, as it attempts to read the response, which is null:

private String sendGet(String url) throws Exception {

    URL obj = new URL(url);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();

    // optional default is GET
    con.setRequestMethod("GET");

    int responseCode = con.getResponseCode();

    System.out.println("Response Code : " + responseCode);

    BufferedReader in = new BufferedReader(
            new InputStreamReader(con.getInputStream()));
    String inputLine;
    StringBuffer response = new StringBuffer();

    while ((inputLine = in.readLine()) != null) {
        response.append(inputLine);
    }

    in.close();

    return "SUCCESS";

}

As a matter of fact, when I attempt to read the responseCode, an Exception is thrown:

java.net.UnknownHostException: namespace.192.168.42.204.nip.io/rest
    at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:184)
    at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
    at java.net.Socket.connect(Socket.java:589)
    at java.net.Socket.connect(Socket.java:538)
    at sun.net.NetworkClient.doConnect(NetworkClient.java:180)
    at sun.net.www.http.HttpClient.openServer(HttpClient.java:463)
    at sun.net.www.http.HttpClient.openServer(HttpClient.java:558)
    at sun.net.www.http.HttpClient.<init>(HttpClient.java:242)
    at sun.net.www.http.HttpClient.New(HttpClient.java:339)
    at sun.net.www.http.HttpClient.New(HttpClient.java:357)
    at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(HttpURLConnection.java:1220)
    at sun.net.www.protocol.http.HttpURLConnection.plainConnect0(HttpURLConnection.java:1156)
    at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:1050)
    at sun.net.www.protocol.http.HttpURLConnection.connect(HttpURLConnection.java:984)
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1564)
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1492)
    at java.net.HttpURLConnection.getResponseCode(HttpURLConnection.java:480)

is it possible to emulate cURL behavior in Java? It would be needed to send the GET Request without reading the response. Do you know any way to do it in Java ?

PiGo :

If there is nothing to read, maybe you could just call connect

con.connect();
con.close();

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=117253&siteId=1