• 原因: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,使用以下代码绿色代码:
    import com.google.api.client.http.ByteArrayContent;
    import com.google.api.client.http.GenericUrl;
    import com.google.api.client.http.HttpBackOffUnsuccessfulResponseHandler;
    import com.google.api.client.http.HttpContent;
    import com.google.api.client.http.HttpHeaders;
    import com.google.api.client.http.HttpRequest;
    import com.google.api.client.http.HttpRequestFactory;
    import com.google.api.client.http.HttpResponse;
    import com.google.api.client.http.HttpStatusCodes;
    import com.google.api.client.http.HttpTransport;
    import com.google.api.client.http.apache.ApacheHttpTransport;
    import com.google.api.client.util.BackOff;
    import java.io.IOException;
    import java.io.InputStream;
    import java.net.ProxySelector;
    import java.util.Map;
    import java.util.Timer;
    import java.util.TimerTask;
    import java.util.concurrent.TimeUnit;
    import javax.annotation.PreDestroy;
    import lombok.Data;
    import lombok.extern.slf4j.Slf4j;
    import org.apache.http.HeaderElement;
    import org.apache.http.HeaderElementIterator;
    import org.apache.http.HttpHost;
    import org.apache.http.conn.ClientConnectionManager;
    import org.apache.http.conn.ConnectionKeepAliveStrategy;
    import org.apache.http.conn.params.ConnManagerParams;
    import org.apache.http.conn.params.ConnPerRouteBean;
    import org.apache.http.conn.scheme.PlainSocketFactory;
    import org.apache.http.conn.scheme.Scheme;
    import org.apache.http.conn.scheme.SchemeRegistry;
    import org.apache.http.conn.ssl.SSLSocketFactory;
    import org.apache.http.impl.client.DefaultHttpClient;
    import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;
    import org.apache.http.impl.conn.ProxySelectorRoutePlanner;
    import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
    import org.apache.http.message.BasicHeaderElementIterator;
    import org.apache.http.params.BasicHttpParams;
    import org.apache.http.params.HttpConnectionParams;
    import org.apache.http.params.HttpParams;
    import org.apache.http.protocol.HTTP;
    import org.apache.http.protocol.HttpContext; /**
    * @author Li Sheng
    */
    @Slf4j
    public class HttpClientUtils { private static HttpRequestFactory requestFactory;
    private static HttpTransport httpTransport;
    private static final String CONTENT_TYPE_JSON = "application/json"; private static final int CACHE_SIZE = 4096; static { HttpParams params = new BasicHttpParams();
    HttpConnectionParams.setStaleCheckingEnabled(params, false);
    HttpConnectionParams.setSocketBufferSize(params, 245760); // 8k(8192) * 30
    ConnManagerParams.setMaxTotalConnections(params, 400);
    ConnManagerParams.setMaxConnectionsPerRoute(params, new ConnPerRouteBean(200)); SchemeRegistry registry = new SchemeRegistry();
    registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    registry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
    ClientConnectionManager connectionManager = new ThreadSafeClientConnManager(params, registry); DefaultHttpClient defaultHttpClient = new DefaultHttpClient(connectionManager, params);
    defaultHttpClient.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler(0, false));
    defaultHttpClient
    .setRoutePlanner(new ProxySelectorRoutePlanner(registry, ProxySelector.getDefault())); ConnectionKeepAliveStrategy connectionKeepAliveStrategy = new ConnectionKeepAliveStrategy() {
    @Override
    public long getKeepAliveDuration(org.apache.http.HttpResponse httpResponse,
    HttpContext httpContext) {
    return 20 * 1000; // 20 seconds,because tomcat default keep-alive timeout is 20s
    }
    };
    defaultHttpClient.setKeepAliveStrategy(connectionKeepAliveStrategy); httpTransport = new ApacheHttpTransport(defaultHttpClient); requestFactory = httpTransport.createRequestFactory(); } @Data
    public static class PostParam { private Integer connectTimeoutMills; // 可选,默认 20s
    private Integer readTimeoutMills; // 可选,默认 20s
    private Map<String, String> headers; // 可选
    private String url; //必填
    private String postJson; //必填
    private Boolean readResponseData; //必填:是否需要读取数据。如果不需要返回结果,设置 false
    private BackOff backOff; //可选,重试机制策略
    private String authorization; //可选 public PostParam(String url, String postJson, boolean readResponseData) {
    this.url = url;
    this.postJson = postJson;
    this.readResponseData = readResponseData;
    }
    } public static String postWithJson(PostParam postParam) {
    GenericUrl genericUrl = new GenericUrl(postParam.getUrl());
    HttpContent httpContent = ByteArrayContent.fromString(null, postParam.getPostJson());
    HttpResponse httpResponse = null;
    try {
    HttpRequest httpRequest = requestFactory.buildPostRequest(genericUrl, httpContent);
    if (postParam.getConnectTimeoutMills() != null) {
    httpRequest.setConnectTimeout(postParam.getConnectTimeoutMills());
    }
    if (postParam.getReadTimeoutMills() != null) {
    httpRequest.setReadTimeout(postParam.getReadTimeoutMills());
    }
    if (postParam.getBackOff() != null) {
    httpRequest.setUnsuccessfulResponseHandler(
    new HttpBackOffUnsuccessfulResponseHandler(postParam.getBackOff()));
    } HttpHeaders httpHeaders = new HttpHeaders();
    httpHeaders.setContentType(CONTENT_TYPE_JSON);
    Map<String, String> headers = postParam.getHeaders();
    if (headers != null && headers.size() > 0) {
    headers.forEach(httpHeaders::set);
    }
    if (postParam.getAuthorization() != null && !postParam.equals("")) {
    httpHeaders.setAuthorization(postParam.getAuthorization());
    } httpRequest.setHeaders(httpHeaders);
    httpResponse = httpRequest.execute();
    if (httpResponse.getStatusCode() != HttpStatusCodes.STATUS_CODE_OK) {
    log.error("http status not 200. param:{},status:{},msg:{}", postParam,
    httpResponse.getStatusCode(), httpResponse.getStatusMessage());
    return null;
    }
    Boolean readResponseData = postParam.getReadResponseData();
    if (readResponseData != null && readResponseData) {
    InputStream inputStream = httpResponse.getContent();
    if (inputStream != null) {
    StringBuffer out = new StringBuffer();
    byte[] b = new byte[CACHE_SIZE];
    for (int n; (n = inputStream.read(b)) != -1; ) {
    out.append(new String(b, 0, n));
    }
    return out.toString();
    }
    }
    } catch (Exception e) {
    log.error("post exception,param:{}", postParam, e);
    } finally {
    try {
    if (httpResponse != null) {
    httpResponse.disconnect();
    }
    } catch (Exception e) {
    log.error("httpResponse disconnect exception", e);
    }
    }
    return null;
    } @PreDestroy
    public static void destory() {
    try {
    log.info("httpTransport shutdown now....");
    httpTransport.shutdown();
    } catch (IOException e) {
    log.error("shut down httpTransport exception", e);
    }
    } }
  • 如果想使用上面的 HttpClientUtils,必须引入 google-httpclient:
    •    <dependency>
      <groupId>com.google.http-client</groupId>
      <artifactId>google-http-client</artifactId>
      <version>1.22.0</version>
      </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. oracle ROW_NUMBER用法

    Oracle中row_number().rank().dense_rank() 的区别 row_number的用途非常广泛,排序最好用它,它会为查询出来的每一行记录生成一个序号,依次排序且不会重复 使 ...

  2. 迷你MVVM框架 avalonjs 0.91发布

    本版本修了一些BUG与不合理的地方,感谢感谢ztz, 民工精髓, 姚立, qiangtou等人指正. 处理AMD加载 旧式IE下移除script节点内存泄漏的问题 fix firefox 全系列vis ...

  3. Shader.WarmupAllShaders

    [Shader.WarmupAllShaders]

  4. linux shell脚本编程笔记(五): 重定向

    I/O重定向 简述: 默认情况下始终有3个"文件"处于打开状态, stdin (键盘), stdout (屏幕), and stderr (错误消息输出到屏幕上). 这3个文件和其 ...

  5. Java设计模式(7)——装饰者模式

    转载:http://blog.csdn.net/yanbober/article/details/45395747 一.装饰者模式的定义 装饰者( Decorator )模式又叫做包装模式.通过一种对 ...

  6. Django模板层

    一:模板简介 二:模板语法值变量 三: 模板之过滤器 四: 模板之标签 五:自定义标签和过滤器   一:模板简介 def current_datetime(request): now=datetime ...

  7. 实战:MySQL Sending data导致查询很慢的问题详细分析(转)

    出处:http://blog.csdn.net/yunhua_lee/article/details/8573621 这两天帮忙定位一个MySQL查询很慢的问题,定位过程综合各种方法.理论.工具,很有 ...

  8. HDU 2036 改革春风吹满地 (计算几何)

    题意:你懂得. 析:没什么可说的,求面积用叉乘,尽量不要用海伦公式,因为计算量大,而且精度损失. 代码如下: #include <iostream> #include <cstdio ...

  9. swift UITabelVIew - 纯代码自定义tabelViewCell

    // //  CustomTableViewCell.swift //  tab // //  Created by su on 15/12/7. //  Copyright © 2015年 tian ...

  10. (DP)To The Max --HDU -- 1081

    链接: http://acm.hdu.edu.cn/showproblem.php?pid=1081 这道题使用到的算法是:预处理+最大连续子串和 如果会做最大连续子串和,那么理解这题就相对简单一些, ...