当前位置: 首页>>代码示例>>Java>>正文


Java RequestConfig.custom方法代码示例

本文整理汇总了Java中org.apache.http.client.config.RequestConfig.custom方法的典型用法代码示例。如果您正苦于以下问题:Java RequestConfig.custom方法的具体用法?Java RequestConfig.custom怎么用?Java RequestConfig.custom使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在org.apache.http.client.config.RequestConfig的用法示例。


在下文中一共展示了RequestConfig.custom方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: testHttpRequestGet

import org.apache.http.client.config.RequestConfig; //导入方法依赖的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: initImpl

import org.apache.http.client.config.RequestConfig; //导入方法依赖的package包/类
private synchronized void initImpl() {
	if (impl == null) {
		HttpClientBuilder builder = createBuilder();

		if (receiveTimeout != null) {
			RequestConfig.Builder requestBuilder = RequestConfig.custom();
			requestBuilder = requestBuilder.setSocketTimeout(receiveTimeout);
			builder.setDefaultRequestConfig(requestBuilder.build());
		}

		for (HttpClientAdapterListener listener : listeners) {
			listener.onBuild(builder);
		}
		impl = builder.build();
	}
}
 
开发者ID:crnk-project,项目名称:crnk-framework,代码行数:17,代码来源:HttpClientAdapter.java

示例3: initRequestConfig

import org.apache.http.client.config.RequestConfig; //导入方法依赖的package包/类
private static RequestConfig initRequestConfig(HiTSDBConfig config) {
	RequestConfig requestConfig = null;

	// 设置请求
	int httpConnectTimeout = config.getHttpConnectTimeout();
	// 需要设置
	if (httpConnectTimeout >= 0) {
		RequestConfig.Builder requestConfigBuilder = RequestConfig.custom();
		// ConnectTimeout:连接超时.连接建立时间,三次握手完成时间.
		requestConfigBuilder.setConnectTimeout(httpConnectTimeout * 1000);
		// SocketTimeout:Socket请求超时.数据传输过程中数据包之间间隔的最大时间.
		requestConfigBuilder.setSocketTimeout(httpConnectTimeout * 1000);
		// ConnectionRequestTimeout:httpclient使用连接池来管理连接,这个时间就是从连接池获取连接的超时时间,可以想象下数据库连接池
		requestConfigBuilder.setConnectionRequestTimeout(httpConnectTimeout * 1000);
		requestConfig = requestConfigBuilder.build();
	}

	return requestConfig;
}
 
开发者ID:aliyun,项目名称:HiTSDB-Client,代码行数:20,代码来源:HttpClientFactory.java

示例4: createRequestConfigBuilder

import org.apache.http.client.config.RequestConfig; //导入方法依赖的package包/类
public RequestConfig.Builder createRequestConfigBuilder(SiteConfig siteConfig, Request request, HttpHost proxy) {
    RequestConfig.Builder requestConfigBuilder = RequestConfig.custom();

    requestConfigBuilder.setConnectTimeout(siteConfig.getConnectTimeout());
    requestConfigBuilder.setSocketTimeout(siteConfig.getSocketTimeout());
    requestConfigBuilder.setRedirectsEnabled(siteConfig.isRedirectsEnabled());
    requestConfigBuilder.setConnectionRequestTimeout(siteConfig.getConnectionRequestTimeout());
    requestConfigBuilder.setCircularRedirectsAllowed(siteConfig.isCircularRedirectsAllowed());
    requestConfigBuilder.setMaxRedirects(siteConfig.getMaxRedirects());
    requestConfigBuilder.setCookieSpec(siteConfig.getCookieSpec());
    requestConfigBuilder.setProxy(proxy);

    return requestConfigBuilder;
}
 
开发者ID:brucezee,项目名称:jspider,代码行数:15,代码来源:HttpClientFactory.java

示例5: createHttpClient

import org.apache.http.client.config.RequestConfig; //导入方法依赖的package包/类
private HttpClient createHttpClient(Authentication auth, String verify, HttpHost target, Boolean postRedirects,
		String password, TrustStrategy keystoreTrustStrategy, HostnameVerifier keystoreHostnameVerifier,
		Proxy proxy) {
	Certificate certificate = new Certificate();
	Auth authHelper = new Auth();
	HttpClientBuilder httpClientBuilder = WinHttpClients.custom();
	Builder requestConfig = RequestConfig.custom();
	requestConfig.setCookieSpec(CookieSpecs.DEFAULT);

	logger.debug("Verify value: " + verify);
	logger.debug((new File(verify).getAbsolutePath()));

	if (new File(verify).exists()) {
		logger.debug("Loading custom keystore");
		httpClientBuilder.setSSLSocketFactory(
				certificate.allowAllCertificates(certificate.createCustomKeyStore(verify.toString(), password),
						password, keystoreTrustStrategy, keystoreHostnameVerifier));
	} else if (!Boolean.parseBoolean(verify.toString())) {
		logger.debug("Allowing all certificates");
		httpClientBuilder.setSSLSocketFactory(certificate.allowAllCertificates(null));
	}

	if (auth.isAuthenticable()) {
		httpClientBuilder.setDefaultCredentialsProvider(authHelper.getCredentialsProvider(auth, target));
	}

	if (proxy != null && proxy.isInUse()) {
		logger.debug("Enabling proxy");
		if (proxy.isAuthenticable()) {
			logger.debug("Setting proxy credentials");
			httpClientBuilder.setDefaultCredentialsProvider(
					authHelper.getCredentialsProvider(proxy.getAuth(), proxy.getHttpHost()));
		}
		requestConfig.setProxy(proxy.getHttpHost());
	}

	if (postRedirects) {
		httpClientBuilder.setRedirectStrategy(new CustomRedirectStrategy());
	}
	httpClientBuilder.setDefaultRequestConfig(requestConfig.build());

	return httpClientBuilder.build();
}
 
开发者ID:Hi-Fi,项目名称:httpclient,代码行数:44,代码来源:RestClient.java

示例6: getRequest

import org.apache.http.client.config.RequestConfig; //导入方法依赖的package包/类
public HttpRequestBase getRequest(){
	String url = getUrl();
	HttpRequestBase request = getRequest(url);
	if(!headers.isEmpty()){
		for(Entry<String,List<String>> header : headers.entrySet()){
			for(String headerValue : header.getValue()){
				request.addHeader(header.getKey(), headerValue);
			}
		}
	}
	if(entity != null && canHaveEntity()){
		((HttpEntityEnclosingRequest) request).setEntity(entity);
	}
	if(timeoutMs != null || proxy != null){
		Builder builder = RequestConfig.custom();
		builder.setCookieSpec(CookieSpecs.STANDARD);
		if(timeoutMs != null){
			builder.setConnectTimeout(timeoutMs).setConnectionRequestTimeout(timeoutMs).setSocketTimeout(timeoutMs);
		}
		if(proxy != null){
			builder.setProxy(proxy);
		}

		RequestConfig requestConfig = builder.build();
		request.setConfig(requestConfig);
	}
	return request;
}
 
开发者ID:hotpads,项目名称:datarouter,代码行数:29,代码来源:DatarouterHttpRequest.java

示例7: initRestTemplate

import org.apache.http.client.config.RequestConfig; //导入方法依赖的package包/类
/**
 * springboot初始化restTemplate
 */
@Bean
public RestTemplate initRestTemplate() {
    // 长连接保持30秒
    PoolingHttpClientConnectionManager pollingConnectionManager = new PoolingHttpClientConnectionManager(30, TimeUnit.SECONDS);
    // 总连接数
    pollingConnectionManager.setMaxTotal(1000);
    // 同路由的并发数
    pollingConnectionManager.setDefaultMaxPerRoute(1000);

    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
    httpClientBuilder.setConnectionManager(pollingConnectionManager);
    // 重试次数,默认是3次,没有开启
    httpClientBuilder.setRetryHandler(new DefaultHttpRequestRetryHandler(2, true));
    // 保持长连接配置,需要在头添加Keep-Alive
    httpClientBuilder.setKeepAliveStrategy(new DefaultConnectionKeepAliveStrategy());

    RequestConfig.Builder builder = RequestConfig.custom();
    builder.setConnectionRequestTimeout(200);
    builder.setConnectTimeout(5000);
    builder.setSocketTimeout(5000);

    RequestConfig requestConfig = builder.build();
    httpClientBuilder.setDefaultRequestConfig(requestConfig);

    List<Header> headers = new ArrayList<>();
    headers.add(new BasicHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.16 Safari/537.36"));
    headers.add(new BasicHeader("Accept-Encoding", "gzip,deflate"));
    headers.add(new BasicHeader("Accept-Language", "zh-CN"));
    headers.add(new BasicHeader("Connection", "Keep-Alive"));

    httpClientBuilder.setDefaultHeaders(headers);

    HttpClient httpClient = httpClientBuilder.build();

    // httpClient连接配置,底层是配置RequestConfig
    HttpComponentsClientHttpRequestFactory clientHttpRequestFactory = new HttpComponentsClientHttpRequestFactory(httpClient);
    // 连接超时
    clientHttpRequestFactory.setConnectTimeout(5000);
    // 数据读取超时时间,即SocketTimeout
    clientHttpRequestFactory.setReadTimeout(5000);
    // 连接不够用的等待时间,不宜过长,必须设置,比如连接不够用时,时间过长将是灾难性的
    clientHttpRequestFactory.setConnectionRequestTimeout(200);
    // 缓冲请求数据,默认值是true。通过POST或者PUT大量发送数据时,建议将此属性更改为false,以免耗尽内存。
    clientHttpRequestFactory.setBufferRequestBody(false);

    // 添加内容转换器
    List<HttpMessageConverter<?>> messageConverters = new ArrayList<>();
    messageConverters.add(initStringHttpMessageConverter());
    messageConverters.add(new FormHttpMessageConverter());
    messageConverters.add(new MappingJackson2XmlHttpMessageConverter());
    messageConverters.add(new MappingJackson2HttpMessageConverter());

    RestTemplate restTemplate = new RestTemplate(messageConverters);
    restTemplate.setRequestFactory(clientHttpRequestFactory);
    restTemplate.setErrorHandler(new DefaultResponseErrorHandler());
    return restTemplate;

}
 
开发者ID:wu05281,项目名称:admin-shiro,代码行数:62,代码来源:RestTemplateConfig.java

示例8: generateHttpRequest

import org.apache.http.client.config.RequestConfig; //导入方法依赖的package包/类
protected HttpUriRequest generateHttpRequest(Site site,Request request,HttpHost proxy){
	RequestBuilder requestBuilder = selectRequestMethod(request).setUri(request.getUrl());
       if (site.getHeaders() != null) {
           for (Map.Entry<String, String> headerEntry : site.getHeaders().entrySet()) {
               requestBuilder.setHeader(headerEntry.getKey(), headerEntry.getValue());
           }
       }
       RequestConfig.Builder requestConfigBuilder = RequestConfig.custom();
       if (site != null) {
           requestConfigBuilder.setConnectionRequestTimeout(site.getTimeout())
                   .setSocketTimeout(site.getTimeout())
                   .setConnectTimeout(site.getTimeout())
                   .setCookieSpec(CookieSpecs.STANDARD);
       }

       if (proxy != null) {
           requestConfigBuilder.setProxy(proxy);
       }
       requestBuilder.setConfig(requestConfigBuilder.build());
       HttpUriRequest httpUriRequest = requestBuilder.build();
       if (request.getHeaders() != null && !request.getHeaders().isEmpty()) {
           for (Map.Entry<String, String> header : request.getHeaders().entrySet()) {
               httpUriRequest.setHeader(header.getKey(), header.getValue());
           }
       }
       return httpUriRequest;
}
 
开发者ID:xbynet,项目名称:crawler,代码行数:28,代码来源:AbsDownloader.java

示例9: initClient

import org.apache.http.client.config.RequestConfig; //导入方法依赖的package包/类
private void initClient( String accessKey, String secretKey, List<Header> defaultHeadersOverride, int connectionRequestTimeout, int connectionTimeout, int socketTimeout, HttpHost proxy, boolean noSslValidation, String impersonateUsername ) {
    RequestConfig.Builder requestConfigBuilder = RequestConfig.custom();

    requestConfigBuilder.setConnectionRequestTimeout( connectionRequestTimeout ).setConnectTimeout( connectionTimeout ).setSocketTimeout( socketTimeout );
    if( proxy != null )
        requestConfigBuilder.setProxy( proxy );

    SSLContext sslContext = null;
    // Note: this block of code disables SSL validation. It is only used during development/testing when testing through a proxy
    if( noSslValidation ) {
        try {
            sslContext = SSLContexts.custom().loadTrustMaterial( new TrustStrategy() {
                @Override
                public boolean isTrusted( X509Certificate[] chain, String authType ) throws CertificateException {
                    return true;
                }
            } )
                    .build();
        } catch( Exception e ) {
        }
    }

    //system properties
    Map<String, String> systemProperties = ManagementFactory.getRuntimeMXBean().getSystemProperties();

    if ( defaultHeadersOverride == null ) {
        defaultHeaders = new ArrayList<>( 3 );
        defaultHeaders.add( new BasicHeader( "X-ApiKeys", String.format( "accessKey=%s; secretKey=%s", accessKey, secretKey ) ) );
        defaultHeaders.add( new BasicHeader( "User-Agent", String.format( "TenableIOSDK Java/%s %s/%s/%s", systemProperties.get( "java.runtime.version" ), systemProperties.get( "os.name" ), systemProperties.get( "os.version" ), systemProperties.get( "os.arch" ) ) ) );
        defaultHeaders.add( new BasicHeader( "Accept", "*/*" ) );

        if ( impersonateUsername != null ) {
            defaultHeaders.add( new BasicHeader( "X-Impersonate", "username=" + impersonateUsername ) );
        }
    } else {
        defaultHeaders = defaultHeadersOverride;
    }

    asyncClient = HttpAsyncClients.custom()
            .setDefaultRequestConfig( requestConfigBuilder.build() )
            .setDefaultHeaders( defaultHeaders )
            .setSSLContext( sslContext )
            .build();

    asyncClient.start();
}
 
开发者ID:tenable,项目名称:Tenable.io-SDK-for-Java,代码行数:47,代码来源:AsyncHttpService.java

示例10: init

import org.apache.http.client.config.RequestConfig; //导入方法依赖的package包/类
/**
 * Initialization method.  This takes in the configuration and sets up the underlying
 * http client appropriately.
 * @param configuration The user defined configuration.
 */
@Override
public void init(final Configuration configuration) {
    // Save reference to configuration
    this.configuration = configuration;

    // Create default SSLContext
    final SSLContext sslcontext = SSLContexts.createDefault();

    // Allow TLSv1 protocol only
    final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
        sslcontext,
        new String[] { "TLSv1" },
        null,
        SSLConnectionSocketFactory.getDefaultHostnameVerifier()
    );

    // Setup client builder
    final HttpClientBuilder clientBuilder = HttpClientBuilder.create();
    clientBuilder
        // Pardot disconnects requests after 120 seconds.
        .setConnectionTimeToLive(130, TimeUnit.SECONDS)
        .setSSLSocketFactory(sslsf);

    // Define our RequestConfigBuilder
    final RequestConfig.Builder requestConfigBuilder = RequestConfig.custom();

    // If we have a configured proxy host
    if (configuration.getProxyHost() != null) {
        // Define proxy host
        final HttpHost proxyHost = new HttpHost(
            configuration.getProxyHost(),
            configuration.getProxyPort(),
            configuration.getProxyScheme()
        );

        // If we have proxy auth enabled
        if (configuration.getProxyUsername() != null) {
            // Create credential provider
            final CredentialsProvider credsProvider = new BasicCredentialsProvider();
            credsProvider.setCredentials(
                new AuthScope(configuration.getProxyHost(), configuration.getProxyPort()),
                new UsernamePasswordCredentials(configuration.getProxyUsername(), configuration.getProxyPassword())
            );

            // Attach Credentials provider to client builder.
            clientBuilder.setDefaultCredentialsProvider(credsProvider);
        }

        // Attach Proxy to request config builder
        requestConfigBuilder.setProxy(proxyHost);
    }

    // Attach default request config
    clientBuilder.setDefaultRequestConfig(requestConfigBuilder.build());

    // build http client
    httpClient = clientBuilder.build();
}
 
开发者ID:Crim,项目名称:pardot-java-client,代码行数:64,代码来源:HttpClientRestClient.java


注:本文中的org.apache.http.client.config.RequestConfig.custom方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。