如何在InputStreamReader上设置超时?

时间:2015-07-26 17:56:55

标签: java api http request 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秒?

1 个答案:

答案 0 :(得分:2)

您可以在HTTP连接上设置超时,如: -

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