在android使用httpclient時出現“SocketException: Broken Pipe”的解決方案

來源:互聯網
上載者:User
原因分析:

1.用戶端與伺服器的連結已經關閉(可能是用戶端,也可能使伺服器端,一般是用戶端主動關閉),用戶端繼續向服務端寫資料;

2.在使用httpclient的threadsafeconnectionmanager或者poolconnectionmanger的時候容易出現,原因是我們設定了串連擷取資料逾時的時間;

解決方案:

1.為你的httpclient添加retry handler,形如下代碼:

         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去重試進行串連;

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.