如何在 InputStreamReader 上设置超时?

How to set timeout on InputStreamReader?

所以我目前有这个在 Java:

中做一个 HTTP 请求
HttpURLConnection connection = (HttpURLConnection) apiURL.openConnection();

connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Accept", "application/json");
connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
writer.write(payload);
writer.close();

JSONObject json = (JSONObject) new JSONParser().parse(new InputStreamReader(connection.getInputStream()));
connection.disconnect();

我看到很多人提到套接字,但我不确定它在这里如何应用。我如何将此 HTTP 请求的超时设置为 1 秒?

您可以像这样设置 HTTP 连接超时:-

 connection.setConnectTimeout(5000); // 5 seconds connectTimeout
 connection.setReadTimeout(5000 ); // 5 seconds socketTimeout