簡體   English   中英

簡單的 Java Http 客戶端程序不起作用

[英]Simple Java Http Client program is not working

我創建了一個簡單的客戶端程序,但它在發送請求后不起作用並卡住了。
調試時它卡在這里 - 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());

        }

    }

}

每個 HttpURLConnection 實例用於發出單個請求,但與 HTTP 服務器的底層網絡連接可能由其他實例透明地共享。 在請求之后調用 HttpURLConnection 的 InputStream 或 OutputStream 上的 close() 方法可能會釋放與此實例關聯的網絡資源,但對任何共享的持久連接沒有影響。 如果持久連接當時處於空閑狀態,則調用 disconnect() 方法可能會關閉底層套接字 Java 文檔

可能在調試期間,您使用相同的實例進行多次調用,這在文檔中是不允許的。 您應該創建另一個實例或調用斷開連接,然后再次向同一個實例調用 openConnection 以進行另一個調用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM