在android使用httpclient时出现“SocketException: Broken Pipe”的解决方法

原因分析:

1.客户端与服务器的链接已经关闭(可能是客户端,也可能使服务器端,一般是客户端主动关闭),客户端继续向服务端写数据;

2.在使用httpclient的threadsafeconnectionmanager或者poolconnectionmanger的时候容易出现,原因是我们设置了连接获取数据超时的时间;

解决方法:

1.为你的httpclient添加retryhandler,形如下代码:

         HttpRequestRetryHandler retryHandler = new HttpRequestRetryHandler() {

            @Override
            public boolean retryRequest(IOException arg0, int arg1, HttpContext arg2) {
                // retry a max of 5 times
                if (arg1 >= 3) {
                    return false;
                }
                if (arg0 instanceof ch.boye.httpclientandroidlib.NoHttpResponseException) {
                    return true;
                } else if (arg0 instanceof ch.boye.httpclientandroidlib.client.ClientProtocolException) {
                    return true;
                }
                return false;
            }
        };
        sHttpClient.setHttpRequestRetryHandler(retryHandler);

2.处理SocketException:

    InputStream in = null;
 try {
 final HttpResponse response = HttpManager.execute(context, post);
 final int statusCode = response.getStatusLine().getStatusCode();
 if (statusCode == HttpStatus.SC_OK) {
     HttpEntity entity = response.getEntity();
 if (entity != null) {
 in = entity.getContent();
 return IOUtils.stream2String(in);
 }
 } else {
 post.abort();
 mLog.error("http code: " + response.getStatusLine().getStatusCode());
 }
 } catch (IOException ex) {
 post.abort();
 } catch (RuntimeException ex) {
 post.abort();
 throw ex;
 } finally {
 IOUtils.closeStream(in);
 }
SocketExcption是IOException的子类,当发现有IO异常的时候主动关闭该连接,而又httpClient去重试进行连接;


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值