當前位置: 首頁>>代碼示例>>Java>>正文


Java HttpClients.custom方法代碼示例

本文整理匯總了Java中org.apache.http.impl.client.HttpClients.custom方法的典型用法代碼示例。如果您正苦於以下問題:Java HttpClients.custom方法的具體用法?Java HttpClients.custom怎麽用?Java HttpClients.custom使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在org.apache.http.impl.client.HttpClients的用法示例。


在下文中一共展示了HttpClients.custom方法的14個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: testHttpRequestGet

import org.apache.http.impl.client.HttpClients; //導入方法依賴的package包/類
@Test
public void testHttpRequestGet() throws Exception {

    RequestConfig.Builder req = RequestConfig.custom();
    req.setConnectTimeout(5000);
    req.setConnectionRequestTimeout(5000);
    req.setRedirectsEnabled(false);
    req.setSocketTimeout(5000);
    req.setExpectContinueEnabled(false);

    HttpGet get = new HttpGet("http://127.0.0.1:54322/login");
    get.setConfig(req.build());

    PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
    cm.setDefaultMaxPerRoute(5);

    HttpClientBuilder builder = HttpClients.custom();
    builder.disableAutomaticRetries();
    builder.disableRedirectHandling();
    builder.setConnectionTimeToLive(5, TimeUnit.SECONDS);
    builder.setKeepAliveStrategy(DefaultConnectionKeepAliveStrategy.INSTANCE);
    builder.setConnectionManager(cm);
    CloseableHttpClient client = builder.build();

    String s = client.execute(get, new ResponseHandler<String>() {

        @Override
        public String handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
            assertEquals(301, response.getStatusLine().getStatusCode());
            return "success";
        }

    });
    assertEquals("success", s);

}
 
開發者ID:NationalSecurityAgency,項目名稱:qonduit,代碼行數:37,代碼來源:HTTPStrictTransportSecurityIT.java

示例2: createHttpClientBuilder

import org.apache.http.impl.client.HttpClients; //導入方法依賴的package包/類
protected HttpClientBuilder createHttpClientBuilder(SiteConfig siteConfig) {
    HttpClientBuilder httpClientBuilder = HttpClients.custom();

    httpClientBuilder.setConnectionTimeToLive(siteConfig.getConnTimeToLiveMillis(), TimeUnit.MILLISECONDS);
    httpClientBuilder.setMaxConnPerRoute(siteConfig.getMaxConnPerRoute());
    httpClientBuilder.setMaxConnTotal(siteConfig.getMaxConnTotal());
    httpClientBuilder.setUserAgent(siteConfig.getUserAgent());

    httpClientBuilder.setRetryHandler(createHttpRequestRetryHandler());
    httpClientBuilder.setRedirectStrategy(createRedirectStrategy());
    httpClientBuilder.setSSLContext(createSSLContext());
    httpClientBuilder.setSSLHostnameVerifier(createSSLHostnameVerifier());

    httpClientBuilder.setDefaultConnectionConfig(createConnectionConfig(siteConfig));
    httpClientBuilder.setDefaultSocketConfig(createSocketConfig(siteConfig));
    httpClientBuilder.setDefaultCookieSpecRegistry(createCookieSpecRegistry());
    httpClientBuilder.setDefaultCookieStore(createCookieStore());

    return httpClientBuilder;
}
 
開發者ID:brucezee,項目名稱:jspider,代碼行數:21,代碼來源:HttpClientFactory.java

示例3: createBuilder

import org.apache.http.impl.client.HttpClients; //導入方法依賴的package包/類
private HttpClientBuilder createBuilder() {
	// brave enforces this, hopefully can be removed again eventually

	HttpClientBuilder builder = null;
	for (HttpClientAdapterListener listener : listeners) {
		if (listener instanceof HttpClientBuilderFactory) {
			PreconditionUtil
					.assertNull("only one module can contribute a HttpClientBuilder with HttpClientBuilderFactory", builder);
			builder = ((HttpClientBuilderFactory) listener).createBuilder();
		}
	}

	if (builder != null) {
		return builder;
	}
	else {
		return HttpClients.custom();
	}

}
 
開發者ID:crnk-project,項目名稱:crnk-framework,代碼行數:21,代碼來源:HttpClientAdapter.java

示例4: getEntity

import org.apache.http.impl.client.HttpClients; //導入方法依賴的package包/類
private String getEntity(URI url) throws IOException {
    final HttpGet get = new HttpGet(url);
    get.setConfig(requestConfig);
    get.setHeader("Accept", "application/json");

    HttpClientBuilder clientBuilder = HttpClients.custom();
    if (sslContext != null) {
        clientBuilder.setSslcontext(sslContext);
    }

    try (CloseableHttpClient httpClient = clientBuilder.build()) {

        try (CloseableHttpResponse response = httpClient.execute(get)) {

            final StatusLine statusLine = response.getStatusLine();
            final int statusCode = statusLine.getStatusCode();
            if (200 != statusCode) {
                final String msg = String.format("Failed to get entity from %s, response=%d:%s",
                        get.getURI(), statusCode, statusLine.getReasonPhrase());
                throw new RuntimeException(msg);
            }
            final HttpEntity entity = response.getEntity();
            return EntityUtils.toString(entity);
        }
    }
}
 
開發者ID:bcgov,項目名稱:nifi-atlas,代碼行數:27,代碼來源:NiFiApiClient.java

示例5: getHttpClient

import org.apache.http.impl.client.HttpClients; //導入方法依賴的package包/類
public HttpClient getHttpClient() {
	if (httpClient == null) {
		synchronized (this) {
			if (httpClient == null) {
				if (pool == null) { //初始化pool
					try {
						afterPropertiesSet();
					} catch (Exception e) {
						logger.error(e.getMessage(), e);
					}
				}

				HttpClientBuilder httpClientBuilder = HttpClients.custom();
				httpClientBuilder.setConnectionManager(pool);
				httpClientBuilder.setDefaultRequestConfig(RequestConfig.custom().setConnectTimeout(conntimeout).setSocketTimeout(sotimeout).build());
				httpClientBuilder.setKeepAliveStrategy(new ConnectionKeepAliveStrategy() {
					public long getKeepAliveDuration(HttpResponse response, HttpContext context) {
						HeaderElementIterator it = new BasicHeaderElementIterator(response.headerIterator(HTTP.CONN_KEEP_ALIVE));
						while (it.hasNext()) {
							HeaderElement he = it.nextElement();
							String param = he.getName();
							String value = he.getValue();
							if (value != null && param.equalsIgnoreCase("timeout")) {
								try {
									return Long.parseLong(value) * 1000;
								} catch (NumberFormatException ignore) {
								}
							}
						}
						// 否則保持活動5秒
						return 5 * 1000;
					}
				});
				httpClient = httpClientBuilder.build();
			}
		}
	}
	return httpClient;
}
 
開發者ID:funtl,項目名稱:framework,代碼行數:40,代碼來源:HttpClientUtil.java

示例6: createHttpClient

import org.apache.http.impl.client.HttpClients; //導入方法依賴的package包/類
/**
 * 獲取Http客戶端連接對象
 * @param timeOut 超時時間
 * @param proxy   代理
 * @param cookie  Cookie
 * @return Http客戶端連接對象
 */
public CloseableHttpClient createHttpClient(int timeOut,HttpHost proxy,BasicClientCookie cookie) {

    // 創建Http請求配置參數
    RequestConfig.Builder builder = RequestConfig.custom()
            // 獲取連接超時時間
            .setConnectionRequestTimeout(timeOut)
            // 請求超時時間
            .setConnectTimeout(timeOut)
            // 響應超時時間
            .setSocketTimeout(timeOut)
            .setCookieSpec(CookieSpecs.STANDARD);

    if (proxy!=null) {
        builder.setProxy(proxy);
    }

    RequestConfig requestConfig = builder.build();

    // 創建httpClient
    HttpClientBuilder httpClientBuilder = HttpClients.custom();

    httpClientBuilder
            // 把請求相關的超時信息設置到連接客戶端
            .setDefaultRequestConfig(requestConfig)
            // 把請求重試設置到連接客戶端
            .setRetryHandler(new RetryHandler())
            // 配置連接池管理對象
            .setConnectionManager(connManager);

    if (cookie!=null) {
        CookieStore cookieStore = new BasicCookieStore();
        cookieStore.addCookie(cookie);
        httpClientBuilder.setDefaultCookieStore(cookieStore);
    }

    return httpClientBuilder.build();
}
 
開發者ID:fengzhizi715,項目名稱:NetDiscovery,代碼行數:45,代碼來源:HttpManager.java

示例7: createHttpClient

import org.apache.http.impl.client.HttpClients; //導入方法依賴的package包/類
/**
 * 獲取Http客戶端連接對象
 * @param timeOut 超時時間
 * @param proxy   代理
 * @param cookie  Cookie
 * @return Http客戶端連接對象
 */
private CloseableHttpClient createHttpClient(int timeOut,HttpHost proxy,BasicClientCookie cookie) {

    // 創建Http請求配置參數
    RequestConfig.Builder builder = RequestConfig.custom()
            // 獲取連接超時時間
            .setConnectionRequestTimeout(timeOut)
            // 請求超時時間
            .setConnectTimeout(timeOut)
            // 響應超時時間
            .setSocketTimeout(timeOut)
            .setCookieSpec(CookieSpecs.STANDARD);

    if (proxy!=null) {
        builder.setProxy(proxy);
    }

    RequestConfig requestConfig = builder.build();

    // 創建httpClient
    HttpClientBuilder httpClientBuilder = HttpClients.custom();

    httpClientBuilder
            // 把請求相關的超時信息設置到連接客戶端
            .setDefaultRequestConfig(requestConfig)
            // 把請求重試設置到連接客戶端
            .setRetryHandler(new RetryHandler())
            // 配置連接池管理對象
            .setConnectionManager(connManager);

    if (cookie!=null) {
        CookieStore cookieStore = new BasicCookieStore();
        cookieStore.addCookie(cookie);
        httpClientBuilder.setDefaultCookieStore(cookieStore);
    }

    return httpClientBuilder.build();
}
 
開發者ID:fengzhizi715,項目名稱:PicCrawler,代碼行數:45,代碼來源:HttpManager.java

示例8: getHttpClient

import org.apache.http.impl.client.HttpClients; //導入方法依賴的package包/類
/**
 * Construct httpclient with SSL protocol
 *
 * @param clientConfiguration the client configuration
 * @return {@code CloseableHttpClient}
 * @throws Exception
 */
public static CloseableHttpClient getHttpClient(ClientConfiguration clientConfiguration) throws Exception {
    if (clientConfiguration == null) {
        clientConfiguration = new ClientConfiguration();
    }

    SSLConnectionSocketFactory sslSocketFactory = createSslConnectionSocketFactory(clientConfiguration);
    HttpClientBuilder builder = HttpClients.custom();

    // set proxy
    String proxyHost = clientConfiguration.getProxyHost();
    int proxyPort = clientConfiguration.getProxyPort();

    if (!StringUtils.isEmpty(proxyHost) && proxyPort > 0) {
        HttpHost proxy = new HttpHost(proxyHost, proxyPort);
        builder.setProxy(proxy);

        String username = clientConfiguration.getProxyUserName();
        String password = clientConfiguration.getProxyPassword();

        if (!StringUtils.isEmpty(username) && !StringUtils.isEmpty(password)) {
            CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            AuthScope authscope = new AuthScope(proxy);
            Credentials credentials = new UsernamePasswordCredentials(username,
                    password);
            credentialsProvider.setCredentials(authscope, credentials);
            builder.setDefaultCredentialsProvider(credentialsProvider);
        }
    }
    builder.setUserAgent(VersionUtil.getDefaultUserAgent());
    CloseableHttpClient httpclient = builder.setSSLSocketFactory(sslSocketFactory).build();
    return httpclient;
}
 
開發者ID:SimpleMessageNotification,項目名稱:smn-sdk-java,代碼行數:40,代碼來源:HttpUtil.java

示例9: createClient

import org.apache.http.impl.client.HttpClients; //導入方法依賴的package包/類
private ConnectionManagerAwareHttpClient createClient(ApacheSdkHttpClientFactory configuration,
                                                      AttributeMap standardOptions) {
    final HttpClientBuilder builder = HttpClients.custom();
    // Note that it is important we register the original connection manager with the
    // IdleConnectionReaper as it's required for the successful deregistration of managers
    // from the reaper. See https://github.com/aws/aws-sdk-java/issues/722.
    final HttpClientConnectionManager cm = cmFactory.create(configuration, standardOptions);

    builder.setRequestExecutor(new HttpRequestExecutor())
           // SDK handles decompression
           .disableContentCompression()
           .setKeepAliveStrategy(buildKeepAliveStrategy(configuration))
           .disableRedirectHandling()
           .disableAutomaticRetries()
           .setUserAgent("") // SDK will set the user agent header in the pipeline. Don't let Apache waste time
           .setConnectionManager(ClientConnectionManagerFactory.wrap(cm));

    addProxyConfig(builder, configuration.proxyConfiguration());

    // TODO idle connection reaper
    //        if (.useReaper()) {
    //            IdleConnectionReaper.registerConnectionManager(cm, settings.getMaxIdleConnectionTime());
    //        }

    return new ApacheSdkClient(builder.build(), cm);
}
 
開發者ID:aws,項目名稱:aws-sdk-java-v2,代碼行數:27,代碼來源:ApacheHttpClientFactory.java

示例10: usingHttpComponents

import org.apache.http.impl.client.HttpClients; //導入方法依賴的package包/類
static ClientHttpRequestFactory usingHttpComponents(ClientOptions options,
                                                    SslConfiguration sslConfiguration) throws GeneralSecurityException,
        IOException {

    HttpClientBuilder httpClientBuilder = HttpClients.custom();

    httpClientBuilder.setRoutePlanner(new SystemDefaultRoutePlanner(
            DefaultSchemePortResolver.INSTANCE, ProxySelector.getDefault()));

    if (hasSslConfiguration(sslConfiguration)) {

        SSLContext sslContext = getSSLContext(sslConfiguration);
        SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(
                sslContext);
        httpClientBuilder.setSSLSocketFactory(sslSocketFactory);
        httpClientBuilder.setSslcontext(sslContext);
    }

    RequestConfig requestConfig = RequestConfig.custom()
            .setConnectTimeout(options.getConnectionTimeout())
            .setSocketTimeout(options.getReadTimeout())
            .setAuthenticationEnabled(true)
            .build();

    httpClientBuilder.setDefaultRequestConfig(requestConfig);

    // Support redirects
    httpClientBuilder.setRedirectStrategy(new LaxRedirectStrategy());

    // Fix weird problem `ProtocolException: Content-Length header already present` from `org.apache.http.protocol.RequestContent`
    httpClientBuilder.addInterceptorFirst(new HttpRequestInterceptor() {
        @Override
        public void process(HttpRequest request, HttpContext context) throws HttpException, IOException {
            if (request instanceof HttpEntityEnclosingRequest) {
                request.removeHeaders(HTTP.TRANSFER_ENCODING);
                request.removeHeaders(HTTP.CONTENT_LEN);
            }
        }
    });

    return new HttpComponentsClientHttpRequestFactory(httpClientBuilder.build());
}
 
開發者ID:JetBrains,項目名稱:teamcity-hashicorp-vault-plugin,代碼行數:43,代碼來源:ClientHttpRequestFactoryFactory.java

示例11: initialzeInternalClient

import org.apache.http.impl.client.HttpClients; //導入方法依賴的package包/類
protected void initialzeInternalClient() {

        if (!needsInternalClientInialization) {
            // internal client is already initialized
            return;
        }

        // release any resources if this client was already used
        close();

        // rebuild the client
        HttpClientBuilder httpClientBuilder = HttpClients.custom();

        // Add this interceptor to get the values of all HTTP headers in the request.
        // Some of them are provided by the user while others are generated by Apache HTTP Components.
        httpClientBuilder.addInterceptorLast(new HttpRequestInterceptor() {
            @Override
            public void process( HttpRequest request, HttpContext context ) throws HttpException,
                                                                            IOException {

                Header[] requestHeaders = request.getAllHeaders();
                actualRequestHeaders = new ArrayList<HttpHeader>();
                for (Header header : requestHeaders) {
                    addHeaderToList(actualRequestHeaders, header.getName(), header.getValue());
                }
                if (debugLevel != HttpDebugLevel.NONE) {
                    logHTTPRequest(requestHeaders, request);
                }
            }
        });

        // connect and read timeouts
        httpClientBuilder.setDefaultRequestConfig(RequestConfig.custom()
                                                               .setConnectTimeout(connectTimeoutSeconds
                                                                                  * 1000)
                                                               .setSocketTimeout(readTimeoutSeconds
                                                                                 * 1000)
                                                               .build());

        // socket buffer size
        if (this.socketBufferSize > 0) {
            httpClientBuilder.setDefaultSocketConfig(SocketConfig.custom()
                                                                 .setRcvBufSize(this.socketBufferSize)
                                                                 .setSndBufSize(this.socketBufferSize)
                                                                 .build());
        }

        // SSL
        if (isOverSsl) {
            setupSSL(httpClientBuilder);
        }

        // setup authentication
        if (!StringUtils.isNullOrEmpty(username)) {
            setupAuthentication(httpClientBuilder);
        }

        // set proxy
        if (AtsSystemProperties.SYSTEM_HTTP_PROXY_HOST != null
            && AtsSystemProperties.SYSTEM_HTTP_PROXY_PORT != null) {

            HttpHost proxy = new HttpHost(AtsSystemProperties.SYSTEM_HTTP_PROXY_HOST,
                                          Integer.parseInt(AtsSystemProperties.SYSTEM_HTTP_PROXY_PORT));
            DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy);
            httpClientBuilder.setRoutePlanner(routePlanner);
        }

        // now build the client after we have already set everything needed on the client builder
        httpClient = httpClientBuilder.build();

        // do not come here again until not needed
        needsInternalClientInialization = false;
    }
 
開發者ID:Axway,項目名稱:ats-framework,代碼行數:74,代碼來源:HttpClient.java

示例12: build

import org.apache.http.impl.client.HttpClients; //導入方法依賴的package包/類
/**
 * @param listener Log listener
 * @param prompt   Prompt for proxy credentials
 * @return Builder for HTTP client
 */
public HttpClientBuilder build(final TranscriptListener listener, final LoginCallback prompt) {
    final HttpClientBuilder configuration = HttpClients.custom();
    // Use HTTP Connect proxy implementation provided here instead of
    // relying on internal proxy support in socket factory
    final Proxy proxy = proxyFinder.find(host);
    switch(proxy.getType()) {
        case HTTP:
        case HTTPS:
            final HttpHost h = new HttpHost(proxy.getHostname(), proxy.getPort(), StringUtils.lowerCase(proxy.getType().name()));
            if(log.isInfoEnabled()) {
                log.info(String.format("Setup proxy %s", h));
            }
            configuration.setProxy(h);
            configuration.setProxyAuthenticationStrategy(new CallbackProxyAuthenticationStrategy(ProxyCredentialsStoreFactory.get(), host, prompt));
            break;
    }
    configuration.setUserAgent(new PreferencesUseragentProvider().get());
    final int timeout = preferences.getInteger("connection.timeout.seconds") * 1000;
    configuration.setDefaultSocketConfig(SocketConfig.custom()
        .setTcpNoDelay(true)
        .setSoTimeout(timeout)
        .build());
    configuration.setDefaultRequestConfig(this.createRequestConfig(timeout));
    final String encoding;
    if(null == host.getEncoding()) {
        encoding = preferences.getProperty("browser.charset.encoding");
    }
    else {
        encoding = host.getEncoding();
    }
    configuration.setDefaultConnectionConfig(ConnectionConfig.custom()
        .setBufferSize(preferences.getInteger("http.socket.buffer"))
        .setCharset(Charset.forName(encoding))
        .build());
    if(preferences.getBoolean("http.connections.reuse")) {
        configuration.setConnectionReuseStrategy(new DefaultClientConnectionReuseStrategy());
    }
    else {
        configuration.setConnectionReuseStrategy(new NoConnectionReuseStrategy());
    }
    configuration.setRetryHandler(new ExtendedHttpRequestRetryHandler(preferences.getInteger("http.connections.retry")));
    configuration.setServiceUnavailableRetryStrategy(new DisabledServiceUnavailableRetryStrategy());
    if(!preferences.getBoolean("http.compression.enable")) {
        configuration.disableContentCompression();
    }
    configuration.setRequestExecutor(new LoggingHttpRequestExecutor(listener));
    // Always register HTTP for possible use with proxy. Contains a number of protocol properties such as the
    // default port and the socket factory to be used to create the java.net.Socket instances for the given protocol
    configuration.setConnectionManager(this.createConnectionManager(this.createRegistry()));
    configuration.setDefaultAuthSchemeRegistry(RegistryBuilder.<AuthSchemeProvider>create()
        .register(AuthSchemes.BASIC, new BasicSchemeFactory(
            Charset.forName(preferences.getProperty("http.credentials.charset"))))
        .register(AuthSchemes.DIGEST, new DigestSchemeFactory(
            Charset.forName(preferences.getProperty("http.credentials.charset"))))
        .register(AuthSchemes.NTLM, new NTLMSchemeFactory())
        .register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory())
        .register(AuthSchemes.KERBEROS, new KerberosSchemeFactory()).build());
    return configuration;
}
 
開發者ID:iterate-ch,項目名稱:cyberduck,代碼行數:65,代碼來源:HttpConnectionPoolBuilder.java

示例13: createHttpClient

import org.apache.http.impl.client.HttpClients; //導入方法依賴的package包/類
private static CloseableHttpClient createHttpClient() {
    HttpClientBuilder httpClientBuilder = HttpClients.custom();
    httpClientBuilder.setSSLSocketFactory(SSL_SOCKET_FACTORY);
    return httpClientBuilder.build();
}
 
開發者ID:pascalgn,項目名稱:jiracli,代碼行數:6,代碼來源:HttpClient.java

示例14: create

import org.apache.http.impl.client.HttpClients; //導入方法依賴的package包/類
@Override
public ConnectionManagerAwareHttpClient create(HttpClientSettings settings) {
    final HttpClientBuilder builder = HttpClients.custom();
    // Note that it is important we register the original connection manager with the
    // IdleConnectionReaper as it's required for the successful deregistration of managers
    // from the reaper. See https://github.com/aws/aws-sdk-java/issues/722.
    final HttpClientConnectionManager cm = cmFactory.create(settings);

    builder.setRequestExecutor(new SdkHttpRequestExecutor())
            .setKeepAliveStrategy(buildKeepAliveStrategy(settings))
            .disableRedirectHandling()
            .disableAutomaticRetries()
            .setConnectionManager(ClientConnectionManagerFactory.wrap(cm));

    // By default http client enables Gzip compression. So we disable it
    // here.
    // Apache HTTP client removes Content-Length, Content-Encoding and
    // Content-MD5 headers when Gzip compression is enabled. Currently
    // this doesn't affect S3 or Glacier which exposes these headers.
    //
    if (!(settings.useGzip())) {
        builder.disableContentCompression();
    }

    HttpResponseInterceptor itcp = new CRC32ChecksumResponseInterceptor();
    if (settings.calculateCRC32FromCompressedData()) {
        builder.addInterceptorFirst(itcp);
    } else {
        builder.addInterceptorLast(itcp);
    }

    addProxyConfig(builder, settings);

    final ConnectionManagerAwareHttpClient httpClient = new SdkHttpClient(builder.build(), cm);

    if (settings.useReaper()) {
        IdleConnectionReaper.registerConnectionManager(cm, settings.getMaxIdleConnectionTime());
    }

    return httpClient;
}
 
開發者ID:IBM,項目名稱:ibm-cos-sdk-java,代碼行數:42,代碼來源:ApacheHttpClientFactory.java


注:本文中的org.apache.http.impl.client.HttpClients.custom方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。