HttpUrlConnection.getInputStream returns empty stream in Android

若如初见. 提交于 2019-12-03 13:06:46

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.

You can try with this code that will return response in String:

public String ReadHttpResponse(String url){
        StringBuilder sb= new StringBuilder();
        HttpClient client= new DefaultHttpClient();     
        HttpGet httpget = new HttpGet(url);     
        try {
            HttpResponse response = client.execute(httpget);
            StatusLine sl = response.getStatusLine();
            int sc = sl.getStatusCode();
            if (sc==200)
            {
                HttpEntity ent = response.getEntity();
                InputStream inpst = ent.getContent();
                BufferedReader rd= new BufferedReader(new InputStreamReader(inpst));
                String line;
                while ((line=rd.readLine())!=null)
                {
                    sb.append(line);
                }
            }
            else
            {
                Log.e("log_tag","I didn't  get the response!");
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return sb.toString();
    }
Amir Amir

The Stream data may not be ready, so you should check in a loop that the data in the stream is available before attempting to access it. Once the data is ready, you should read it and store in another place like a byte array; a binary stream object is a nice choice to read data as a byte array. The reason that a byte array is a better choice is because the data may be binary data like an image file, etc.

InputStream is = httpConnection.getInputStream();

byte[] bytes = null;

ByteArrayOutputStream baos = new ByteArrayOutputStream();

byte[] temp = new byte[is.available()];
while (is.read(temp, 0, temp.length) != -1) {
    baos.write(temp);
    temp = new byte[is.available()];
}

bytes = baos.toByteArray();

In the above code, bytes is the response as byte array. You can convert it to string if it is text data, for example data as utf-8 encoded text:

String text = new String(bytes, Charset.forName("utf-8"));
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!