I am trying to get a String of http response (just a JSON object), and sometimes this piece of code waits infinite time in
line = reader.readLine()
May be, the reason of such behavior is bad Internet connection (I use 3G modem), but I need a stable solution to avoid this infinite lock. What can be done here to avoid it?
HttpResponse response = httpClient.execute(httpPost);
InputStream content = null;
JSONObject json_obj;
if (response.getStatusLine().getStatusCode() == 200) {
HttpEntity entity = response.getEntity();
try {
content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content, "UTF-8"), 256);
StringBuilder sb = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
} catch (Exception e) {}
}
You can specify a read timeout:
Should set a read timeout to 30 seconds.
Probably, you also want to specify a connection timeout: