您的位置:首页 > 理论基础 > 计算机网络

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

2017-06-16 16:14 1136 查看


原因分析:

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

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


解决方法:

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

[java] view
plain copy

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:

[java] view
plain copy

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去重试进行连接;
http://blog.csdn.net/androidzhaoxiaogang/article/details/8153456?utm_source=tuicool&utm_medium=referral
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐