原因分析:
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去重試進行串連;