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

原因分析:

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

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

解决方法:

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

[java]  view plain  copy
  1.  HttpRequestRetryHandler retryHandler = new HttpRequestRetryHandler() {  
  2.   
  3.     @Override  
  4.     public boolean retryRequest(IOException arg0, int arg1, HttpContext arg2) {  
  5.         // retry a max of 5 times  
  6.         if (arg1 >= 3) {  
  7.             return false;  
  8.         }  
  9.         if (arg0 instanceof ch.boye.httpclientandroidlib.NoHttpResponseException) {  
  10.             return true;  
  11.         } else if (arg0 instanceof ch.boye.httpclientandroidlib.client.ClientProtocolException) {  
  12.             return true;  
  13.         }  
  14.         return false;  
  15.     }  
  16. };  
  17. sHttpClient.setHttpRequestRetryHandler(retryHandler);  

2.处理SocketException:

[java]  view plain  copy
  1.     InputStream in = null;  
  2.     try {  
  3.         final HttpResponse response = HttpManager.execute(context, post);  
  4.         final int statusCode = response.getStatusLine().getStatusCode();  
  5.         if (statusCode == HttpStatus.SC_OK) {  
  6.             HttpEntity entity = response.getEntity();  
  7.             if (entity != null) {  
  8.                 in = entity.getContent();  
  9.                 return IOUtils.stream2String(in);  
  10.             }  
  11.         } else {  
  12.             post.abort();  
  13.             mLog.error("http code: " + response.getStatusLine().getStatusCode());  
  14.        }  
  15.     } catch (IOException ex) {  
  16.         post.abort();  
  17.     } catch (RuntimeException ex) {  
  18.         post.abort();  
  19.         throw ex;  
  20.     } finally {  
  21.         IOUtils.closeStream(in);  
  22.     }  
SocketExcption是IOException的子类,当发现有IO异常的时候主动关闭该连接,而又httpClient去重试进行连接;


http://blog.csdn.net/androidzhaoxiaogang/article/details/8153456?utm_source=tuicool&utm_medium=referral



你可能感兴趣的:(java,http)