Search code examples
javaapihttprequestinputstreamreader

How to set timeout on InputStreamReader?


So I have this currently to do a HTTP request in Java:

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?


Solution

  • You can set timeout on HTTP connection like:-

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