org.apache.http.ConnectionReuseStrategy Java Examples

The following examples show how to use org.apache.http.ConnectionReuseStrategy. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: MockHttpClient.java    From google-http-java-client with Apache License 2.0 6 votes vote down vote up
@Override
protected RequestDirector createClientRequestDirector(
    HttpRequestExecutor requestExec,
    ClientConnectionManager conman,
    ConnectionReuseStrategy reustrat,
    ConnectionKeepAliveStrategy kastrat,
    HttpRoutePlanner rouplan,
    HttpProcessor httpProcessor,
    HttpRequestRetryHandler retryHandler,
    RedirectHandler redirectHandler,
    AuthenticationHandler targetAuthHandler,
    AuthenticationHandler proxyAuthHandler,
    UserTokenHandler stateHandler,
    HttpParams params) {
  return new RequestDirector() {
    @Beta
    public HttpResponse execute(HttpHost target, HttpRequest request, HttpContext context)
        throws HttpException, IOException {
      return new BasicHttpResponse(HttpVersion.HTTP_1_1, responseCode, null);
    }
  };
}
 
Example #2
Source File: HttpUtils.java    From rxp-remote-java with MIT License 5 votes vote down vote up
/**
 * Get a default HttpClient based on the HttpConfiguration object. If required the defaults can 
 * be altered to meet the requirements of the SDK user. The default client does not use connection 
 * pooling and does not reuse connections. Timeouts for connection and socket are taken from the 
 * {@link HttpConfiguration} object.
 * 
 * @param httpConfiguration
 * @return CloseableHttpClient
 */
public static CloseableHttpClient getDefaultClient(HttpConfiguration httpConfiguration) {

    RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(httpConfiguration.getTimeout())
            .setSocketTimeout(httpConfiguration.getTimeout()).build();

    HttpClientConnectionManager connectionManager = new BasicHttpClientConnectionManager();
    ConnectionReuseStrategy connectionResuseStrategy = new NoConnectionReuseStrategy();

    logger.debug("Creating HttpClient with simple no pooling/no connection reuse default settings.");
    CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(requestConfig).setConnectionManager(connectionManager)
            .setConnectionReuseStrategy(connectionResuseStrategy).build();
    return httpClient;
}
 
Example #3
Source File: LibHttpClient.java    From YiBo with Apache License 2.0 5 votes vote down vote up
@Override
protected RequestDirector createClientRequestDirector(
        final HttpRequestExecutor requestExec,
        final ClientConnectionManager conman,
        final ConnectionReuseStrategy reustrat,
        final ConnectionKeepAliveStrategy kastrat,
        final HttpRoutePlanner rouplan,
        final HttpProcessor httpProcessor,
        final HttpRequestRetryHandler retryHandler,
        final RedirectHandler redirectHandler,
        final AuthenticationHandler targetAuthHandler,
        final AuthenticationHandler proxyAuthHandler,
        final UserTokenHandler stateHandler,
        final HttpParams params) {
    return new LibRequestDirector(
            requestExec,
            conman,
            reustrat,
            kastrat,
            rouplan,
            httpProcessor,
            retryHandler,
            redirectHandler,
            targetAuthHandler,
            proxyAuthHandler,
            stateHandler,
            params);
}
 
Example #4
Source File: Http4FileProvider.java    From commons-vfs with Apache License 2.0 5 votes vote down vote up
/**
 * Create an {@link HttpClientBuilder} object. Invoked by {@link #createHttpClient(Http4FileSystemConfigBuilder, GenericFileName, FileSystemOptions)}.
 *
 * @param builder Configuration options builder for HTTP4 provider
 * @param rootName The root path
 * @param fileSystemOptions The FileSystem options
 * @return an {@link HttpClientBuilder} object
 * @throws FileSystemException if an error occurs
 */
protected HttpClientBuilder createHttpClientBuilder(final Http4FileSystemConfigBuilder builder, final GenericFileName rootName,
        final FileSystemOptions fileSystemOptions) throws FileSystemException {
    final List<Header> defaultHeaders = new ArrayList<>();
    defaultHeaders.add(new BasicHeader(HTTP.USER_AGENT, builder.getUserAgent(fileSystemOptions)));

    final ConnectionReuseStrategy connectionReuseStrategy = builder.isKeepAlive(fileSystemOptions)
            ? DefaultConnectionReuseStrategy.INSTANCE
            : NoConnectionReuseStrategy.INSTANCE;

    final HttpClientBuilder httpClientBuilder =
            HttpClients.custom()
            .setRoutePlanner(createHttpRoutePlanner(builder, fileSystemOptions))
            .setConnectionManager(createConnectionManager(builder, fileSystemOptions))
            .setSSLContext(createSSLContext(builder, fileSystemOptions))
            .setSSLHostnameVerifier(createHostnameVerifier(builder, fileSystemOptions))
            .setConnectionReuseStrategy(connectionReuseStrategy)
            .setDefaultRequestConfig(createDefaultRequestConfig(builder, fileSystemOptions))
            .setDefaultHeaders(defaultHeaders)
            .setDefaultCookieStore(createDefaultCookieStore(builder, fileSystemOptions));

    if (!builder.getFollowRedirect(fileSystemOptions)) {
        httpClientBuilder.disableRedirectHandling();
    }

    return httpClientBuilder;
}
 
Example #5
Source File: HttpServerConnectionUpnpStream.java    From TVRemoteIME with GNU General Public License v2.0 4 votes vote down vote up
public UpnpHttpService(HttpProcessor processor, ConnectionReuseStrategy reuse, HttpResponseFactory responseFactory) {
    super(processor, reuse, responseFactory);
}
 
Example #6
Source File: TestTwitterSocket.java    From albert with MIT License 4 votes vote down vote up
public static void main(String[] args) throws Exception {
	  OAuthConsumer consumer = new CommonsHttpOAuthConsumer(
				Constants.ConsumerKey,
				Constants.ConsumerSecret);
	  consumer.setTokenWithSecret(Constants.AccessToken, Constants.AccessSecret);
	  
	  
    HttpParams params = new BasicHttpParams();
    // HTTP 协议的版本,1.1/1.0/0.9
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    // 字符集
    HttpProtocolParams.setContentCharset(params, "UTF-8");
    // 伪装的浏览器类型
    // IE7 是 
    // Mozilla/4.0 (compatible; MSIE 7.0b; Windows NT 6.0)
    //
    // Firefox3.03
    // Mozilla/5.0 (Windows; U; Windows NT 5.2; zh-CN; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3
    //
    HttpProtocolParams.setUserAgent(params, "HttpComponents/1.1");
    HttpProtocolParams.setUseExpectContinue(params, true);
    BasicHttpProcessor httpproc = new BasicHttpProcessor();
    httpproc.addInterceptor(new RequestContent());
    httpproc.addInterceptor(new RequestTargetHost());
    httpproc.addInterceptor(new RequestConnControl());
    httpproc.addInterceptor(new RequestUserAgent());
    httpproc.addInterceptor(new RequestExpectContinue());
    HttpRequestExecutor httpexecutor = new HttpRequestExecutor();
    HttpContext context = new BasicHttpContext(null);
    HttpHost host = new HttpHost("127.0.0.1", 1080);
    DefaultHttpClientConnection conn = new DefaultHttpClientConnection();
    ConnectionReuseStrategy connStrategy = new DefaultConnectionReuseStrategy();
    context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
    context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, host);
    try {
      String[] targets = { "https://www.twitter.com"};
      for (int i = 0; i < targets.length; i++) {
        if (!conn.isOpen()) {
          Socket socket = new Socket(host.getHostName(), host.getPort());
          conn.bind(socket, params);
        }
        
	  
        BasicHttpRequest request = new BasicHttpRequest("GET", targets[i]);
//        consumer.sign(request);
        
        System.out.println(">> Request URI: " + request.getRequestLine().getUri());
        context.setAttribute(ExecutionContext.HTTP_REQUEST, request);
        request.setParams(params);
        httpexecutor.preProcess(request, httpproc, context);
        HttpResponse response = httpexecutor.execute(request, conn, context);
        response.setParams(params);
        httpexecutor.postProcess(response, httpproc, context);
        // 返回码
        System.out.println("<< Response: " + response.getStatusLine());
        // 返回的文件头信息
//        Header[] hs = response.getAllHeaders();
//        for (Header h : hs) {
//          System.out.println(h.getName() + ":" + h.getValue());
//        }
        // 输出主体信息
//        System.out.println(EntityUtils.toString(response.getEntity()));
        
        HttpEntity entry = response.getEntity();
        StringBuffer sb = new StringBuffer();
  	  if(entry != null)
  	  {
  	    InputStreamReader is = new InputStreamReader(entry.getContent());
  	    BufferedReader br = new BufferedReader(is);
  	    String str = null;
  	    while((str = br.readLine()) != null)
  	    {
  	     sb.append(str.trim());
  	    }
  	    br.close();
  	  }
  	  System.out.println(sb.toString());
  	  
        System.out.println("==============");
        if (!connStrategy.keepAlive(response, context)) {
          conn.close();
        } else {
          System.out.println("Connection kept alive...");
        }
      }
    } finally {
      conn.close();
    }
  }
 
Example #7
Source File: SimpleHttpClientFactoryBean.java    From springboot-shiro-cas-mybatis with MIT License 4 votes vote down vote up
public ConnectionReuseStrategy getConnectionReuseStrategy() {
    return this.connectionReuseStrategy;
}
 
Example #8
Source File: SimpleHttpClientFactoryBean.java    From springboot-shiro-cas-mybatis with MIT License 4 votes vote down vote up
public void setConnectionReuseStrategy(final ConnectionReuseStrategy connectionReuseStrategy) {
    this.connectionReuseStrategy = connectionReuseStrategy;
}
 
Example #9
Source File: IheHttpFactory.java    From openxds with Apache License 2.0 4 votes vote down vote up
public ConnectionReuseStrategy newConnStrategy() {
    return new DefaultConnectionReuseStrategy();
}
 
Example #10
Source File: HttpServerConnectionUpnpStream.java    From DroidDLNA with GNU General Public License v3.0 4 votes vote down vote up
public UpnpHttpService(HttpProcessor processor, ConnectionReuseStrategy reuse, HttpResponseFactory responseFactory) {
    super(processor, reuse, responseFactory);
}
 
Example #11
Source File: HttpTool.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
public HttpClientBuilder reuseStrategy(ConnectionReuseStrategy val) {
    this.reuseStrategy = checkNotNull(val, "reuseStrategy");
    return this;
}
 
Example #12
Source File: HttpClientFactory.java    From hsac-fitnesse-fixtures with Apache License 2.0 4 votes vote down vote up
public ConnectionReuseStrategy getConnectionReuseStrategy() {
    return connectionReuseStrategy;
}
 
Example #13
Source File: HttpClientFactory.java    From hsac-fitnesse-fixtures with Apache License 2.0 4 votes vote down vote up
public void setConnectionReuseStrategy(ConnectionReuseStrategy connectionReuseStrategy) {
    this.connectionReuseStrategy = connectionReuseStrategy;
}
 
Example #14
Source File: HttpClientFactory.java    From hsac-fitnesse-fixtures with Apache License 2.0 4 votes vote down vote up
protected ConnectionReuseStrategy createConnectionReuseStrategy() {
    return NoConnectionReuseStrategy.INSTANCE;
}
 
Example #15
Source File: LibRequestDirector.java    From YiBo with Apache License 2.0 4 votes vote down vote up
public LibRequestDirector(
        final HttpRequestExecutor requestExec,
        final ClientConnectionManager conman,
        final ConnectionReuseStrategy reustrat,
        final ConnectionKeepAliveStrategy kastrat,
        final HttpRoutePlanner rouplan,
        final HttpProcessor httpProcessor,
        final HttpRequestRetryHandler retryHandler,
        final RedirectHandler redirectHandler,
        final AuthenticationHandler targetAuthHandler,
        final AuthenticationHandler proxyAuthHandler,
        final UserTokenHandler userTokenHandler,
        final HttpParams params) {

    if (requestExec == null) {
        throw new IllegalArgumentException("Request executor may not be null.");
    }
    if (conman == null) {
        throw new IllegalArgumentException("Client connection manager may not be null.");
    }
    if (reustrat == null) {
        throw new IllegalArgumentException("Connection reuse strategy may not be null.");
    }
    if (kastrat == null) {
        throw new IllegalArgumentException("Connection keep alive strategy may not be null.");
    }
    if (rouplan == null) {
        throw new IllegalArgumentException("Route planner may not be null.");
    }
    if (httpProcessor == null) {
        throw new IllegalArgumentException("HTTP protocol processor may not be null.");
    }
    if (retryHandler == null) {
        throw new IllegalArgumentException("HTTP request retry handler may not be null.");
    }
    if (redirectHandler == null) {
        throw new IllegalArgumentException("Redirect handler may not be null.");
    }
    if (targetAuthHandler == null) {
        throw new IllegalArgumentException("Target authentication handler may not be null.");
    }
    if (proxyAuthHandler == null) {
        throw new IllegalArgumentException("Proxy authentication handler may not be null.");
    }
    if (userTokenHandler == null) {
        throw new IllegalArgumentException("User token handler may not be null.");
    }
    if (params == null) {
        throw new IllegalArgumentException("HTTP parameters may not be null");
    }
    this.requestExec       = requestExec;
    this.connManager       = conman;
    this.reuseStrategy     = reustrat;
    this.keepAliveStrategy = kastrat;
    this.routePlanner      = rouplan;
    this.httpProcessor     = httpProcessor;
    this.retryHandler      = retryHandler;
    this.redirectHandler   = redirectHandler;
    this.targetAuthHandler = targetAuthHandler;
    this.proxyAuthHandler  = proxyAuthHandler;
    this.userTokenHandler  = userTokenHandler;
    this.params            = params;

    this.managedConn       = null;

    this.execCount = 0;
    this.redirectCount = 0;
    this.maxRedirects = this.params.getIntParameter(ClientPNames.MAX_REDIRECTS, 100);
    this.targetAuthState = new AuthState();
    this.proxyAuthState = new AuthState();
}