org.apache.http.HttpClientConnection源码实例Demo

类org.apache.http.HttpClientConnection源码实例Demo

下面列出了org.apache.http.HttpClientConnection 类实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: cyberduck   文件: LoggingHttpRequestExecutor.java
@Override
protected HttpResponse doSendRequest(final HttpRequest request, final HttpClientConnection conn, final HttpContext context) throws IOException, HttpException {
    synchronized(listener) {
        listener.log(TranscriptListener.Type.request, request.getRequestLine().toString());
        for(Header header : request.getAllHeaders()) {
            switch(header.getName()) {
                case HttpHeaders.AUTHORIZATION:
                case HttpHeaders.PROXY_AUTHORIZATION:
                case "X-Auth-Key":
                case "X-Auth-Token":
                    listener.log(TranscriptListener.Type.request, String.format("%s: %s", header.getName(),
                            StringUtils.repeat("*", Integer.min(8, StringUtils.length(header.getValue())))));
                    break;
                default:
                    listener.log(TranscriptListener.Type.request, header.toString());
                    break;
            }
        }
    }
    final HttpResponse response = super.doSendRequest(request, conn, context);
    if(null != response) {
        // response received as part of an expect-continue handshake
        this.log(response);
    }
    return response;
}
 
源代码2 项目: ibm-cos-sdk-java   文件: SdkHttpRequestExecutor.java
@Override
protected HttpResponse doReceiveResponse(
        final HttpRequest          request,
        final HttpClientConnection conn,
        final HttpContext          context)
            throws HttpException, IOException {
    AWSRequestMetrics awsRequestMetrics = (AWSRequestMetrics) context
            .getAttribute(AWSRequestMetrics.class.getSimpleName());
    if (awsRequestMetrics == null) {
        return super.doReceiveResponse(request, conn, context);
    }
    awsRequestMetrics.startEvent(Field.HttpClientReceiveResponseTime);
    try {
        return super.doReceiveResponse(request, conn, context);
    } finally {
        awsRequestMetrics.endEvent(Field.HttpClientReceiveResponseTime);
    }
}
 
@Override
public ConnectionRequest requestConnection(HttpRoute route, Object state) {
  return new ConnectionRequest() {

    @Override
    public boolean cancel() {
      // Nothing to do.
      return false;
    }

    @Override
    public HttpClientConnection get(final long timeout, final TimeUnit timeUnit) {
      return connectionFactory.create(route, connectionConfig);
    }
  };
}
 
@Override
public void connect(
    HttpClientConnection connection,
    HttpRoute route,
    int connectTimeout,
    HttpContext context
) throws IOException {
  HttpHost host;

  if (route.getProxyHost() != null) {
    host = route.getProxyHost();
  } else {
    host = route.getTargetHost();
  }

  InetSocketAddress localAddress = route.getLocalSocketAddress();

  ManagedHttpClientConnection managed = (ManagedHttpClientConnection) connection;
  this.connectionOperator.connect(managed, host, localAddress, connectTimeout, this.socketConfig, context);
}
 
@Override
public HttpResponse execute(HttpRequest request, HttpClientConnection conn, HttpContext context) throws IOException, HttpException {
    Timer.Sample timerSample = Timer.start(registry);

    Tag method = Tag.of("method", request.getRequestLine().getMethod());
    Tag uri = Tag.of("uri", uriMapper.apply(request));
    Tag status = STATUS_UNKNOWN;

    Tags routeTags = exportTagsForRoute ? HttpContextUtils.generateTagsForRoute(context) : Tags.empty();

    try {
        HttpResponse response = super.execute(request, conn, context);
        status = response != null ? Tag.of("status", Integer.toString(response.getStatusLine().getStatusCode())) : STATUS_CLIENT_ERROR;
        return response;
    } catch (IOException | HttpException | RuntimeException e) {
        status = STATUS_IO_ERROR;
        throw e;
    } finally {
        Iterable<Tag> tags = Tags.of(extraTags)
                .and(routeTags)
                .and(uri, method, status);

        timerSample.stop(Timer.builder(METER_NAME)
                .description("Duration of Apache HttpClient request execution")
                .tags(tags)
                .register(registry));
    }
}
 
源代码6 项目: cyberduck   文件: UDTProxyConfigurator.java
@Override
public HttpResponse execute(final HttpRequest request, final HttpClientConnection conn, final HttpContext context) throws IOException, HttpException {
    for(Header h : headers) {
        request.addHeader(new BasicHeader(h.getName(), h.getValue()));
    }
    return super.execute(request, conn, context);
}
 
源代码7 项目: cyberduck   文件: LoggingHttpRequestExecutor.java
@Override
public HttpResponse execute(final HttpRequest request, final HttpClientConnection conn, final HttpContext context)
        throws IOException, HttpException {
    if(!request.containsHeader(HttpHeaders.USER_AGENT)) {
        request.addHeader(new BasicHeader(HttpHeaders.USER_AGENT, useragentProvider.get()));
    }
    return super.execute(request, conn, context);
}
 
源代码8 项目: ibm-cos-sdk-java   文件: SdkHttpRequestExecutor.java
@Override
protected HttpResponse doSendRequest(
        final HttpRequest request,
        final HttpClientConnection conn,
        final HttpContext context)
            throws IOException, HttpException {
    AWSRequestMetrics awsRequestMetrics = (AWSRequestMetrics) context
            .getAttribute(AWSRequestMetrics.class.getSimpleName());

    if (awsRequestMetrics == null) {
        return super.doSendRequest(request, conn, context);
    }
    if (conn instanceof ManagedHttpClientConnection) {
        ManagedHttpClientConnection managedConn = (ManagedHttpClientConnection)conn;
        Socket sock = managedConn.getSocket();
        if (sock instanceof SdkMetricsSocket) {
            SdkMetricsSocket sdkMetricsSocket = (SdkMetricsSocket)sock;
            sdkMetricsSocket.setMetrics(awsRequestMetrics);
        } else if (sock instanceof SdkSSLMetricsSocket) {
            SdkSSLMetricsSocket sdkSSLMetricsSocket = (SdkSSLMetricsSocket)sock;
            sdkSSLMetricsSocket.setMetrics(awsRequestMetrics);
        }
    }
    awsRequestMetrics.startEvent(Field.HttpClientSendRequestTime);
    try {
        return super.doSendRequest(request, conn, context);
    } finally {
        awsRequestMetrics.endEvent(Field.HttpClientSendRequestTime);
    }
}
 
@Override
public HttpResponse execute(HttpRequest request, HttpClientConnection conn, HttpContext context) throws IOException, HttpException {
  Timer.Context timerContext = null;
  if (solrMetricsContext != null) {
    timerContext = timer(request).time();
  }
  try {
    return super.execute(request, conn, context);
  } finally {
    if (timerContext != null) {
      timerContext.stop();
    }
  }
}
 
源代码10 项目: lucene-solr   文件: ConnectionReuseTest.java
public void headerRequest(HttpHost target, HttpRoute route, HttpClientConnection conn, PoolingHttpClientConnectionManager cm)
    throws IOException, HttpException {
  HttpRequest req = new BasicHttpRequest("OPTIONS", "*", HttpVersion.HTTP_1_1);

  req.addHeader("Host", target.getHostName());
  if (!conn.isOpen()) {
    // establish connection based on its route info
    cm.connect(conn, route, 1000, context);
    // and mark it as route complete
    cm.routeComplete(conn, route, context);
  }
  conn.sendRequestHeader(req);
  conn.flush();
  conn.receiveResponseHeader();
}
 
@Override
public void releaseConnection(
    HttpClientConnection connection,
    Object newState,
    long validDuration,
    TimeUnit timeUnit
) {
  try {
    connection.close();
  } catch (IOException e) {
    throw new RuntimeException(e);
  }
}
 
源代码12 项目: ache   文件: SimpleHttpFetcher.java
@Override
public HttpResponse execute(HttpRequest request, HttpClientConnection conn, HttpContext context)
        throws IOException, HttpException {
    HttpInetConnection connection = (HttpInetConnection) conn;
    context.setAttribute(HOST_ADDRESS, connection.getRemoteAddress().getHostAddress());
    return super.execute(request, conn, context);
}
 
源代码13 项目: pinpoint   文件: HttpClientIT.java
@Test
public void test() throws Exception {
    HttpClient httpClient = new DefaultHttpClient();
    try {
        HttpPost post = new HttpPost(webServer.getCallHttpUrl());
        post.addHeader("Content-Type", "application/json;charset=UTF-8");

        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        httpClient.execute(post, responseHandler);
    } catch (Exception ignored) {
    } finally {
        if (null != httpClient && null != httpClient.getConnectionManager()) {
            httpClient.getConnectionManager().shutdown();
        }
    }

    PluginTestVerifier verifier = PluginTestVerifierHolder.getInstance();
    verifier.printCache();

    Class<?> connectorClass;
    
    try {
        connectorClass = Class.forName("org.apache.http.impl.conn.ManagedClientConnectionImpl");
    } catch (ClassNotFoundException e) {
        connectorClass = Class.forName("org.apache.http.impl.conn.AbstractPooledConnAdapter");
    }
    
    verifier.verifyTrace(event("HTTP_CLIENT_4_INTERNAL", AbstractHttpClient.class.getMethod("execute", HttpUriRequest.class, ResponseHandler.class)));
    final String hostname = webServer.getHostAndPort();
    verifier.verifyTrace(event("HTTP_CLIENT_4_INTERNAL", connectorClass.getMethod("open", HttpRoute.class, HttpContext.class, HttpParams.class), annotation("http.internal.display", hostname)));
    verifier.verifyTrace(event("HTTP_CLIENT_4", HttpRequestExecutor.class.getMethod("execute", HttpRequest.class, HttpClientConnection.class, HttpContext.class), null, null, hostname, annotation("http.url", "/"), annotation("http.status.code", 200), annotation("http.io", anyAnnotationValue())));
    verifier.verifyTraceCount(0);
}
 
源代码14 项目: esigate   文件: MockConnectionManager.java
@Override
public void releaseConnection(HttpClientConnection conn, Object newState, long validDuration, TimeUnit timeUnit) {
    try {
        conn.close();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
 
源代码15 项目: hugegraph-common   文件: RestClientTest.java
@Test
public void testCleanExecutor() throws Exception {
    // Modify IDLE_TIME 100ms to speed test
    int newIdleTime = 100;
    int newCheckPeriod = newIdleTime + 20;

    RestClient client = new RestClientImpl("/test", 1000, newIdleTime,
                                           10, 5, 200);

    PoolingHttpClientConnectionManager pool;
    pool = Whitebox.getInternalState(client, "pool");
    pool = Mockito.spy(pool);
    Whitebox.setInternalState(client, "pool", pool);
    HttpRoute route = new HttpRoute(HttpHost.create(
                                    "http://127.0.0.1:8080"));
    // Create a connection manually, it will be put into leased list
    HttpClientConnection conn = pool.requestConnection(route, null)
                                    .get(1L, TimeUnit.SECONDS);
    PoolStats stats = pool.getTotalStats();
    int usingConns = stats.getLeased() + stats.getPending();
    Assert.assertGte(1, usingConns);

    // Sleep more than two check periods for busy connection
    Thread.sleep(newCheckPeriod);
    Mockito.verify(pool, Mockito.never()).closeExpiredConnections();
    stats = pool.getTotalStats();
    usingConns = stats.getLeased() + stats.getPending();
    Assert.assertGte(1, usingConns);

    // The connection will be put into available list
    pool.releaseConnection(conn, null, 0, TimeUnit.SECONDS);

    stats = pool.getTotalStats();
    usingConns = stats.getLeased() + stats.getPending();
    Assert.assertEquals(0, usingConns);
    /*
     * Sleep more than two check periods for free connection,
     * ensure connection has been closed
     */
    Thread.sleep(newCheckPeriod);
    Mockito.verify(pool, Mockito.atLeastOnce())
           .closeExpiredConnections();
    Mockito.verify(pool, Mockito.atLeastOnce())
           .closeIdleConnections(newIdleTime, TimeUnit.MILLISECONDS);
}
 
源代码16 项目: cyberduck   文件: LoggingHttpRequestExecutor.java
@Override
protected HttpResponse doReceiveResponse(final HttpRequest request, final HttpClientConnection conn, final HttpContext context) throws HttpException, IOException {
    final HttpResponse response = super.doReceiveResponse(request, conn, context);
    this.log(response);
    return response;
}
 
@Override
public void connect(HttpClientConnection conn, HttpRoute route, int connectTimeout, HttpContext context) throws
                                                                                                         IOException {

}
 
@Override
public void releaseConnection(HttpClientConnection conn,
                              Object newState,
                              long validDuration,
                              TimeUnit timeUnit) {
}
 
@Override
public void releaseConnection(HttpClientConnection conn, Object newState, long validDuration, TimeUnit timeUnit) {}
 
@Override
public void connect(HttpClientConnection conn, HttpRoute route, int connectTimeout, HttpContext context) throws IOException {}
 
@Override
public void upgrade(HttpClientConnection conn, HttpRoute route, HttpContext context) throws IOException {}
 
@Override
public void routeComplete(HttpClientConnection conn, HttpRoute route, HttpContext context) throws IOException {}
 
@Override
public void releaseConnection(HttpClientConnection conn,
                              Object newState,
                              long validDuration,
                              TimeUnit timeUnit) {
}
 
@Override
public HttpClientConnection get(long timeout, TimeUnit tunit) throws InterruptedException, ExecutionException, ConnectionPoolTimeoutException {
    return null;
}
 
源代码25 项目: lucene-solr   文件: ConnectionReuseTest.java
public HttpClientConnection getConn(ConnectionRequest mConn)
    throws InterruptedException, ConnectionPoolTimeoutException, ExecutionException {
  HttpClientConnection conn = mConn.get(30, TimeUnit.SECONDS);

  return conn;
}
 
@Override
public void upgrade(HttpClientConnection connection, HttpRoute route, HttpContext context) throws IOException {
  ManagedHttpClientConnection managed = (ManagedHttpClientConnection) connection;
  this.connectionOperator.upgrade(managed, route.getTargetHost(), context);
}
 
@Override
public void routeComplete(HttpClientConnection conn, HttpRoute route, HttpContext context) {
  // Nothing to do.
}
 
@Override
public void releaseConnection(HttpClientConnection conn, Object newState, long validDuration, TimeUnit timeUnit) {
  this.fallbackConnManager.releaseConnection(conn, newState, validDuration, timeUnit);
}
 
@Override
public void connect(HttpClientConnection conn, HttpRoute route, int connectTimeout, HttpContext context)
    throws IOException {
  this.fallbackConnManager.connect(conn, route, connectTimeout, context);
}
 
@Override
public void upgrade(HttpClientConnection conn, HttpRoute route, HttpContext context) throws IOException {
  this.fallbackConnManager.upgrade(conn, route, context);
}
 
如果文章对您有帮助,请点击页面广告。以鼓励作者做出的努力。
 类所在包
 类方法
 同包方法