HttpUrlConnection.getInputStream returns empty stream in Android
android, httpurlconnection, inputstream
Solution
Trying the code of Tomislav I've got the answer.
My function streamToString() used .available() to sense if there is any data received, and it returns 0 in Android. Surely, I called it too soon.
If I rather use readLine():
class Util {
public static String streamToString(InputStream is) throws IOException {
StringBuilder sb = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
while ((line = rd.readLine()) != null) {
sb.append(line);
}
return sb.toString();
}
}
then, it waits for the data to arrive.
Thanks.
Problem
I make a GET request to a server using HttpUrlConnection. After connecting: - I get response code: 200 - I get response message: OK I get input stream, no exception thrown but: - in a standalone program I get the body of the response, as expected: {"name":"my name","birthday":"01/01/1970","id":"100002215110084"} - in a android activity, the stream is empty (available() == 0), and thus I can't get any text out. Any hint or trail to follow? Thanks. EDIT: here it is the code Please note: I use `import java.net.HttpURLConnection;` This is the standard http Java library. I don't want to use any other external library. In fact I did have problems in android using the library httpclient from apache (some of their anonymous .class can't be used by the apk compiler). Well, the code: ``` URLConnection theConnection; theConnection = new URL("www.example.com?query=value").openConnection(); theConnection.setRequestProperty("Accept-Charset", "UTF-8"); HttpURLConnection httpConn = (HttpURLConnection) theConnection; int responseCode = httpConn.getResponseCode(); String responseMessage = httpConn.getResponseMessage(); InputStream is = null; if (responseCode >= 400) { is = httpConn.getErrorStream(); } else { is = httpConn.getInputStream(); } String resp = responseCode + "\n" + responseMessage + "\n>" + Util.streamToString(is) + "<\n"; return resp; ``` I see: 200 OK the body of the response but only 200 OK in android