HttpURLConnection does not read the whole response

前端 未结 3 2207
-上瘾入骨i
-上瘾入骨i 2021-02-15 11:36

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:42

    If you are reading the whole Message at once you can compare the isr.available() to the expected content lenght. This is how I did it:

    public byte[] readData(HttpURLConnection conn)
            throws IOException, InterruptedException {
        String _connlen = conn.getHeaderField("Content-Length");
        int connlen = Integer.parseInt(_connlen);
        InputStream isr = null;
        byte[] bytes = new byte[connlen];
    
        try {
            isr = conn.getInputStream();
    
            //security count that it doesn't begin to hang
            int maxcounter = 0;
            //wait till all data is avalibal, max 5sec
            while((isr.available() != connlen) && (maxcounter  < 5000)){
                Thread.sleep(1);
                maxcounter++;
            }
            //Throw if not all data could be read
            if(maxcounter >= 5000)
                throw new IllegalAccessError(); 
    
            //read the data         
            if(isr.read(bytes, 0, connlen) < 0)
                throw new IllegalAccessError();     
    
    
        } finally {
            if (isr != null)
                isr.close();
        }
    
        return bytes;
    }
    

提交回复
热议问题