• 原因:httpclient 之前与服务端建立的链接已经失效(例如:tomcat 默认的keep-alive timeout :20s),再次从连接池拿该失效链接进行请求时,就会保存。
  • 解决方法:官方链接:http://hc.apache.org/httpcomponents-client-ga/tutorial/html/connmgmt.html#d5e659
  • 上面官方链接的2.6 解决方法的代码如果报错,可能是自己的httpclient版本 不适用。自己用的是httpclient 4.0.1,使用以下代码绿色代码:
    1. import com.google.api.client.http.ByteArrayContent;
    2. import com.google.api.client.http.GenericUrl;
    3. import com.google.api.client.http.HttpBackOffUnsuccessfulResponseHandler;
    4. import com.google.api.client.http.HttpContent;
    5. import com.google.api.client.http.HttpHeaders;
    6. import com.google.api.client.http.HttpRequest;
    7. import com.google.api.client.http.HttpRequestFactory;
    8. import com.google.api.client.http.HttpResponse;
    9. import com.google.api.client.http.HttpStatusCodes;
    10. import com.google.api.client.http.HttpTransport;
    11. import com.google.api.client.http.apache.ApacheHttpTransport;
    12. import com.google.api.client.util.BackOff;
    13. import java.io.IOException;
    14. import java.io.InputStream;
    15. import java.net.ProxySelector;
    16. import java.util.Map;
    17. import java.util.Timer;
    18. import java.util.TimerTask;
    19. import java.util.concurrent.TimeUnit;
    20. import javax.annotation.PreDestroy;
    21. import lombok.Data;
    22. import lombok.extern.slf4j.Slf4j;
    23. import org.apache.http.HeaderElement;
    24. import org.apache.http.HeaderElementIterator;
    25. import org.apache.http.HttpHost;
    26. import org.apache.http.conn.ClientConnectionManager;
    27. import org.apache.http.conn.ConnectionKeepAliveStrategy;
    28. import org.apache.http.conn.params.ConnManagerParams;
    29. import org.apache.http.conn.params.ConnPerRouteBean;
    30. import org.apache.http.conn.scheme.PlainSocketFactory;
    31. import org.apache.http.conn.scheme.Scheme;
    32. import org.apache.http.conn.scheme.SchemeRegistry;
    33. import org.apache.http.conn.ssl.SSLSocketFactory;
    34. import org.apache.http.impl.client.DefaultHttpClient;
    35. import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;
    36. import org.apache.http.impl.conn.ProxySelectorRoutePlanner;
    37. import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
    38. import org.apache.http.message.BasicHeaderElementIterator;
    39. import org.apache.http.params.BasicHttpParams;
    40. import org.apache.http.params.HttpConnectionParams;
    41. import org.apache.http.params.HttpParams;
    42. import org.apache.http.protocol.HTTP;
    43. import org.apache.http.protocol.HttpContext;
    44.  
    45. /**
    46. * @author Li Sheng
    47. */
    48. @Slf4j
    49. public class HttpClientUtils {
    50.  
    51. private static HttpRequestFactory requestFactory;
    52. private static HttpTransport httpTransport;
    53. private static final String CONTENT_TYPE_JSON = "application/json";
    54.  
    55. private static final int CACHE_SIZE = 4096;
    56.  
    57. static {
    58.  
    59. HttpParams params = new BasicHttpParams();
    60. HttpConnectionParams.setStaleCheckingEnabled(params, false);
    61. HttpConnectionParams.setSocketBufferSize(params, 245760); // 8k(8192) * 30
    62. ConnManagerParams.setMaxTotalConnections(params, 400);
    63. ConnManagerParams.setMaxConnectionsPerRoute(params, new ConnPerRouteBean(200));
    64.  
    65. SchemeRegistry registry = new SchemeRegistry();
    66. registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    67. registry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
    68. ClientConnectionManager connectionManager = new ThreadSafeClientConnManager(params, registry);
    69.  
    70. DefaultHttpClient defaultHttpClient = new DefaultHttpClient(connectionManager, params);
    71. defaultHttpClient.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler(0, false));
    72. defaultHttpClient
    73. .setRoutePlanner(new ProxySelectorRoutePlanner(registry, ProxySelector.getDefault()));
    74.  
    75. ConnectionKeepAliveStrategy connectionKeepAliveStrategy = new ConnectionKeepAliveStrategy() {
    76. @Override
    77. public long getKeepAliveDuration(org.apache.http.HttpResponse httpResponse,
    78. HttpContext httpContext) {
    79. return 20 * 1000; // 20 seconds,because tomcat default keep-alive timeout is 20s
    80. }
    81. };
    82. defaultHttpClient.setKeepAliveStrategy(connectionKeepAliveStrategy);
    83.  
    84. httpTransport = new ApacheHttpTransport(defaultHttpClient);
    85.  
    86. requestFactory = httpTransport.createRequestFactory();
    87.  
    88. }
    89.  
    90. @Data
    91. public static class PostParam {
    92.  
    93. private Integer connectTimeoutMills; // 可选,默认 20s
    94. private Integer readTimeoutMills; // 可选,默认 20s
    95. private Map<String, String> headers; // 可选
    96. private String url; //必填
    97. private String postJson; //必填
    98. private Boolean readResponseData; //必填:是否需要读取数据。如果不需要返回结果,设置 false
    99. private BackOff backOff; //可选,重试机制策略
    100. private String authorization; //可选
    101.  
    102. public PostParam(String url, String postJson, boolean readResponseData) {
    103. this.url = url;
    104. this.postJson = postJson;
    105. this.readResponseData = readResponseData;
    106. }
    107. }
    108.  
    109. public static String postWithJson(PostParam postParam) {
    110. GenericUrl genericUrl = new GenericUrl(postParam.getUrl());
    111. HttpContent httpContent = ByteArrayContent.fromString(null, postParam.getPostJson());
    112. HttpResponse httpResponse = null;
    113. try {
    114. HttpRequest httpRequest = requestFactory.buildPostRequest(genericUrl, httpContent);
    115. if (postParam.getConnectTimeoutMills() != null) {
    116. httpRequest.setConnectTimeout(postParam.getConnectTimeoutMills());
    117. }
    118. if (postParam.getReadTimeoutMills() != null) {
    119. httpRequest.setReadTimeout(postParam.getReadTimeoutMills());
    120. }
    121. if (postParam.getBackOff() != null) {
    122. httpRequest.setUnsuccessfulResponseHandler(
    123. new HttpBackOffUnsuccessfulResponseHandler(postParam.getBackOff()));
    124. }
    125.  
    126. HttpHeaders httpHeaders = new HttpHeaders();
    127. httpHeaders.setContentType(CONTENT_TYPE_JSON);
    128. Map<String, String> headers = postParam.getHeaders();
    129. if (headers != null && headers.size() > 0) {
    130. headers.forEach(httpHeaders::set);
    131. }
    132. if (postParam.getAuthorization() != null && !postParam.equals("")) {
    133. httpHeaders.setAuthorization(postParam.getAuthorization());
    134. }
    135.  
    136. httpRequest.setHeaders(httpHeaders);
    137. httpResponse = httpRequest.execute();
    138. if (httpResponse.getStatusCode() != HttpStatusCodes.STATUS_CODE_OK) {
    139. log.error("http status not 200. param:{},status:{},msg:{}", postParam,
    140. httpResponse.getStatusCode(), httpResponse.getStatusMessage());
    141. return null;
    142. }
    143. Boolean readResponseData = postParam.getReadResponseData();
    144. if (readResponseData != null && readResponseData) {
    145. InputStream inputStream = httpResponse.getContent();
    146. if (inputStream != null) {
    147. StringBuffer out = new StringBuffer();
    148. byte[] b = new byte[CACHE_SIZE];
    149. for (int n; (n = inputStream.read(b)) != -1; ) {
    150. out.append(new String(b, 0, n));
    151. }
    152. return out.toString();
    153. }
    154. }
    155. } catch (Exception e) {
    156. log.error("post exception,param:{}", postParam, e);
    157. } finally {
    158. try {
    159. if (httpResponse != null) {
    160. httpResponse.disconnect();
    161. }
    162. } catch (Exception e) {
    163. log.error("httpResponse disconnect exception", e);
    164. }
    165. }
    166. return null;
    167. }
    168.  
    169. @PreDestroy
    170. public static void destory() {
    171. try {
    172. log.info("httpTransport shutdown now....");
    173. httpTransport.shutdown();
    174. } catch (IOException e) {
    175. log.error("shut down httpTransport exception", e);
    176. }
    177. }
    178.  
    179. }
  • 如果想使用上面的 HttpClientUtils,必须引入 google-httpclient:
      1.   <dependency>
      2. <groupId>com.google.http-client</groupId>
      3. <artifactId>google-http-client</artifactId>
      4. <version>1.22.0</version>
      5. </dependency>

httpclient org.apache.http.NoHttpResponseException: host:端口 failed to respond 错误原因和解决方法的更多相关文章

  1. tomcat filewatchdog but has failed to stop it原因以及解决方法

    停止tomcat,有些时候会报The web application [/XXX] appears to have started a thread named [FileWatchdog] but ...

  2. [转载]mysqlcreate新建用户host使用%,本地无法连接原因及解决方法

    转载自 http://www.2cto.com/database/201307/225781.html mysql,因为root权限过高,所以新建一用户appadmin,权限仅为要用到的数据库.创建语 ...

  3. Apache -- XAMPP Apache 无法启动原因及解决方法

    XAMPP Apache 无法启动原因1(缺少VC运行库): 这个就是我遇到的问题原因,下载安装的XAMPP版本是xampp-win32-1.7.7-VC9,而现有的Windows XP系统又没有安装 ...

  4. Apache服务器出现Forbidden 403错误提示的解决方法总结

    在配置Linux的 Apache服务时,经常会遇到http403错误,我今天配置测试时也出现了,最后解决了,总结了一下.http 403错误是拒绝访问的意思,有很多原因的.还有,这些问题在win平台的 ...

  5. SSH连接时出现Host key verification failed的原因及解决方法

    SSH连接的时候Host key verification failed. [root@cache001 swftools-0.9.0]# ssh 192.168.1.90@@@@@@@@@@@@@@ ...

  6. apache 指定的网络名不再可用 原因及解决方法

    1.出现问题状况: 出现问题网站:http://www.ayyzz.cn/ 前段时间作文大全网出现有时候比较慢,有时候“找不到网页”404错误:另外在error.log里也报错: [Mon May 0 ...

  7. Apache ab压力测试时出现大量的错误原因分析

    最近有一个测试任务,是测试nginx的并发请求到底能够达到多少的, 于是就用ab工具对其进行压力测试. 这压力测试一执行,问题就来了:发起10000次请求,并发100,错误的情况能达到30%--50% ...

  8. 转:Validation of viewstate MAC failed异常的原因及解决方法

    ViewState是一种机制,ASP.NET 使用这种机制来跟踪服务器控件状态值,否则这些值将不作为 HTTP 窗体的一部分而回传.也就是说在页面刷新或者回传的时候控件的值将被清空,我们在aspx.c ...

  9. MySQL Host is blocked because of many connection errors 解决方法

    应用日志提示错误:create connection error, url: jdbc:mysql://10.45.236.235:3306/db_wang?useUnicode=true&c ...

随机推荐

  1. Maven(四-2) Maven pom.xml 配置详解

    转载于:http://niuzhenxin.iteye.com/blog/2042102 什么是pom?    pom作为项目对象模型.通过xml表示maven项目,使用pom.xml来实现.主要描述 ...

  2. UGUI 事件穿透规则

    UGUI事件分为两大类:点击和拖拽. 点击包括 pointerdown, pointerup. 拖拽包括 begindrag, drag, enddrag. 点击事件无穿透:只会被最上层UI响应,不会 ...

  3. jekins测试环境自动化

    最近搭建测试环境自动化,之前都是用机器猫.机器猫的流程大概是这样,开发打包上传到svn,给测试一个svn地址,测试到机器猫上传文件,然后再运行启动. 为了减去开发打包这个环节,所以专用jenkins. ...

  4. php性能优化学习笔记

    编写代码 1.尽可能多的使用内置函数2.比对内置函数的时间复杂度,选择复杂度低的 比如 循环20万次-测试isset 和 array_key_exists 耗时 对比isset.php , array ...

  5. FTP上传下载--python

    import socket import struct import json import subprocess import os class MYTCPServer: address_famil ...

  6. jquery对象的遍历$(selector).each()

    <!DOCTYPE html> <html> <head> <script language="javascript" src=" ...

  7. Greeplum 系列(七) 权限管理

    Greeplum 系列(七) 权限管理 一.角色管理 Role 分为用户(User)和组(Group),用户有 login 权限,组用来管理用户,一般不会有 login 权限.初始化 gp 时创建了一 ...

  8. W-D-S-Nandflash

    1.6410的硬件一上电就会把nandflash前8K的内容拷贝到6410片内内存来,从片内内存0地址开始运行,如果烧写到nandflash里面的程序大于8k,则拷贝到6410片内的8k程序要把nan ...

  9. Caffe 议事(二):从零开始搭建 ResNet 之 网络的搭建(上)

    3.搭建网络: 搭建网络之前,要确保之前编译 caffe 时已经 make pycaffe 了. 步骤1:导入 Caffe 我们首先在 ResNet 文件夹中建立一个 mydemo.py 的文件,本参 ...

  10. Tomcat8 配置APR模式

    首先说明下tomcat connector运行的3中模式及区别: 1)bio 默认的模式,同步阻塞,性能非常低下,没有经过任何优化处理和支持. 2)nio  同步非阻塞,利用java的异步io护理技术 ...