简体   繁体   中英

Simple Java Http Client program is not working

I have created a simple client program but it is not working and getting stuck after sending request.
While debuging it is getting stuck here - int responseCode = httpClient.getResponseCode();

public class ScimClient {


    public static void main(String[] args) throws Exception {
        new ScimClient().sendGet();
    }



    private void sendGet() throws Exception {


        String url = "https://official-joke-api.appspot.com/random_joke";

        HttpURLConnection httpClient =
                (HttpURLConnection) new URL(url).openConnection();

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

        //add request header
        httpClient.setRequestProperty("Content-Type", "application/json");

        int responseCode = httpClient.getResponseCode();
        System.out.println("\nSending 'GET' request to URL : " + url);
        System.out.println("Response Code : " + responseCode);

        try (BufferedReader in = new BufferedReader(
                new InputStreamReader(httpClient.getInputStream()))) {

            StringBuilder response = new StringBuilder();
            String line;

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

            //print result
            System.out.println(response.toString());

        }

    }

}

Each HttpURLConnection instance is used to make a single request but the underlying network connection to the HTTP server may be transparently shared by other instances. Calling the close() methods on the InputStream or OutputStream of an HttpURLConnection after a request may free network resources associated with this instance but has no effect on any shared persistent connection. Calling the disconnect() method may close the underlying socket if a persistent connection is otherwise idle at that time . java docs

Probably during debugging you used the same instance to make multpiple calls which as stated to the docs is not allowed. You should either create another instance or call disconnect and then openConnection again to the same instance to make another call.

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