一区二区三区日韩精品-日韩经典一区二区三区-五月激情综合丁香婷婷-欧美精品中文字幕专区

分享

httpclient org.apache.http.NoHttpResponseException: host:端口 failed to respond 錯(cuò)誤原因和解決方法

 微雨漸落 2018-05-08
復(fù)制代碼
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;  // 可選,默認(rèn) 20s
    private Integer readTimeoutMills;  // 可選,默認(rèn) 20s
    private Map<String, String> headers; // 可選
    private String url; //必填
    private String postJson; //必填
    private Boolean readResponseData; //必填:是否需要讀取數(shù)據(jù)。如果不需要返回結(jié)果,設(shè)置 false
    private BackOff backOff; //可選,重試機(jī)制策略
    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);
    }
  }

}
復(fù)制代碼

    本站是提供個(gè)人知識(shí)管理的網(wǎng)絡(luò)存儲(chǔ)空間,所有內(nèi)容均由用戶發(fā)布,不代表本站觀點(diǎn)。請(qǐng)注意甄別內(nèi)容中的聯(lián)系方式、誘導(dǎo)購(gòu)買(mǎi)等信息,謹(jǐn)防詐騙。如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請(qǐng)點(diǎn)擊一鍵舉報(bào)。
    轉(zhuǎn)藏 分享 獻(xiàn)花(0

    0條評(píng)論

    發(fā)表

    請(qǐng)遵守用戶 評(píng)論公約

    類似文章 更多

    国产伦精品一区二区三区精品视频 | 国产91色综合久久高清| 精品一区二区三区免费看| 亚洲精品偷拍视频免费观看| 性感少妇无套内射在线视频| 国产又爽又猛又粗又色对黄| 国产精品日韩精品最新| 国产精品免费视频久久| 日本精品免费在线观看| 手机在线不卡国产视频| 欧美大粗爽一区二区三区| 亚洲一区二区三区国产| 亚洲中文字幕一区三区| 一区二区日本一区二区欧美| 男女激情视频在线免费观看| 91麻豆精品欧美一区| 亚洲专区一区中文字幕| 国产一区二区久久综合| 一个人的久久精彩视频 | 开心久久综合激情五月天| 爱草草在线观看免费视频| 国产精品欧美一级免费| 久久女同精品一区二区| 免费精品一区二区三区| 亚洲中文字幕综合网在线| 日韩夫妻午夜性生活视频| 青青操成人免费在线视频| 国产日韩欧美国产欧美日韩 | 国产精品国三级国产专不卡| 91亚洲国产日韩在线| 成人午夜视频精品一区| 午夜精品国产精品久久久| 国产精品福利一级久久| 少妇一区二区三区精品| 亚洲中文字幕综合网在线| 亚洲欧美日韩综合在线成成| 日本人妻熟女一区二区三区| 99国产一区在线播放| 亚洲精品有码中文字幕在线观看| 亚洲中文字幕熟女丝袜久久| 久久本道综合色狠狠五月|