简体   繁体   English

如何在InputStreamReader上设置超时?

[英]How to set timeout on InputStreamReader?

So I have this currently to do a HTTP request in Java: 所以我目前正在用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();

I've seen lots of mention of sockets, but I'm not sure how it applies here. 我已经看到很多关于套接字的提法,但是我不确定它在这里如何应用。 How would I set a timeout on this HTTP request to say 1 second? 我将如何对此HTTP请求设置超时,使其说1秒?

You can set timeout on HTTP connection like:- 您可以在HTTP连接上设置超时,例如:

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

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

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