简体   繁体   English

简单的 Java Http 客户端程序不起作用

[英]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();调试时它卡在这里 - 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.每个 HttpURLConnection 实例用于发出单个请求,但与 HTTP 服务器的底层网络连接可能由其他实例透明地共享。 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.在请求之后调用 HttpURLConnection 的 InputStream 或 OutputStream 上的 close() 方法可能会释放与此实例关联的网络资源,但对任何共享的持久连接没有影响。 Calling the disconnect() method may close the underlying socket if a persistent connection is otherwise idle at that time .如果持久连接当时处于空闲状态,则调用 disconnect() 方法可能会关闭底层套接字 java docs Java 文档

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.您应该创建另一个实例或调用断开连接,然后再次向同一个实例调用 openConnection 以进行另一个调用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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