例外是在DataInputStream.readFully的第197行中抛出的EOFException。 原因是流读取完成后,高速缓存未满而触发的异常。 这是因为实际内容比Content-Length短。
eofexceptionifthisinputstreamreachestheendbeforereadingallthebytes.publicfinalvoidreadfully (byteb [ ],int off,intlen ) int n=0; while(nlen ) intcount=in.read,off n,len - n ); if(count0) throw new EOFException ); //返回异常n =count; }公共字符串主体(httpservletrequesthsr ) throwsioexception ) string contentlength=HSR.get header ) content-length byte datainputstreamdis=new data inputstream (HSR.get inputstream () ); dis.readfully(buffer; 返回新字符串(buffer,' UTF-8 ' ); }
那么,为什么Content-Length的长度与实际不符呢? 我注意到了以下两个属性
' Accept-Encoding':'gzip ',' content-type ':' application/x-www-form-urlencoded ',application/x-www
gzip :使用lem pel-ziv代码(腼腆的葡萄柚77 )的压缩格式,附带32位CRC。
引用官方文档的说明:
bydefaultthisimplementationofhttpurlconnectionrequeststhatserversusegzipcompression.sincegetcontentlength youcannotusethatmethodtopredicthowmanybytescanbereadfromgetinputstream,Instead, readthatstreamuntilitisexhausted 3360 when read (returns-1.gzipcompressioncanbedisabledbysettingtheaccceptableeencodingsinthead
缺省情况下,此HttpURLConnection实现对请求服务器使用gzip压缩。 getContentLength ()返回已传输的字节数,因此此方法无法预测从(getInputStream ) )读取的字节数。 而是在read ()返回-1时读取流,直到不再存在。 可以通过为请求标头设置可接受的编码来禁用Gzip压缩
当两者重叠时,以字符形式传递的参数仍然以gzip格式进行压缩,使Content-Length的长度大于实际长度,从而触发EOFException。
问题解决了,但让我困惑的是,看完就这样回来就好了,为什么还要放弃这个异常呢?