使用HttpUrlConnection执行Post请求,出现EOFException

执行更换头像操作,使用HttpUrlConnection执行Post请求,将头像上传,发现有时候会出现以下异常:

java.io.EOFException
at libcore.io.Streams.readAsciiLine(Streams.java:203)
at libcore.net.http.HttpEngine.readResponseHeaders(HttpEngine.java:560)
at libcore.net.http.HttpEngine.readResponse(HttpEngine.java:813)
at libcore.net.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:274)
at libcore.net.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:168)


执行post请求的部分代码如下:
......
try {
URL url = new URL(urlString);
connection = (HttpURLConnection)url.openConnection();
connection.setConnectTimeout(TIME_OUT_MILLIS);
connection.setReadTimeout(TIME_OUT_MILLIS);
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setUseCaches(false);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

byte[] bytes = postData.getBytes();
connection.setFixedLengthStreamingMode(bytes.length);
        OutputStream os = new BufferedOutputStream(connection.getOutputStream()); 
        os.write(bytes);
        connection.connect();
            
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        result = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
result.append(line);
}
reader.close();
} catch (MalformedURLException e) {
       ......
}
......

网上查阅资料,很多人的解决办法都是在代码中添加如下代码:

connection.setRequestProperty("Connection", "close");

可是我加上之后问题依然存在,进一步研究发现,只有在登录之后第一次执行更换头像请求才会抛出该异常,从第二次开始就不会抛出该异常,查看服务端,发现成功情况下,客户端会把数据分几节发送,完整发送后才断开连接,而出现异常的情况下,客户端在发送一节数据之后就断开了连接,导致读取服务端返回结果是出现了上述异常。
继续查阅资料,其中一个如下:
https://code.google.com/p/google-http-java-client/issues/detail?id=213
网上大多数人的说法是这是HttpUrlConnection的bug,而且是出现在Android 4.x 版本上
于是用Android 2.3版本机子进行多次测试,发现没有了以上的异常

仔细分析,觉得造成此问题是因为连接重用的问题,即更新头像的Post请求用的是登录Get请求所用的连接,这样子出现上面的现象也解释得通,于是对登录的Get请求添加以下代码:
connection.setRequestProperty("Connection", "close");
发现不再有异常抛出
因为http 1.0中默认是关闭的,需要在http头加入"Connection: Keep-Alive",才能启用Keep-Alive;http 1.1中默认启用Keep-Alive,如果加入"Connection: close ",才关闭
所以为避免连接重用,在登录Get请求之后关闭连接,
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值