HttpURLConnection does not read the whole response

前端 未结 3 1346
迷失自我
迷失自我 2021-02-15 11:37

I use HttpURLConnection to do HTTP POST but I dont always get back the full response. I wanted to debug the problem, but when I step through each line it worked. I thought it mu

3条回答
  •  佛祖请我去吃肉
    2021-02-15 11:39

    I think your problem is in this line:

    while (is.available() > 0) {
    

    According to the javadoc, available does not block and wait until all data is available, so you might get the first packet and then it will return false. The proper way to read from an InputStream is like this:

    int len;
    byte[] buffer = new byte[4096];
    while (-1 != (len = in.read(buffer))) {
      bos.write(buffer, 0, len);
    }
    

    Read will return -1 when there nothing left in the inputstream or the connection is closed, and it will block and wait for the network while doing so. Reading arrays is also much more performant than using single bytes.

提交回复
热议问题