Java Code Examples for org.apache.http.client.config.RequestConfig#Builder
The following examples show how to use
org.apache.http.client.config.RequestConfig#Builder .
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: HttpRequestUtil.java From Alice-LiveMan with GNU Affero General Public License v3.0 | 6 votes |
public static HttpResponse getHttpResponse(URI url, String cookies, Map<String, String> requestProperties) throws IOException { HttpGet httpGet = new HttpGet(url); HttpClientContext context = HttpClientContext.create(); RequestConfig.Builder builder = RequestConfig.custom(); builder.setConnectTimeout(30000).setConnectionRequestTimeout(30000).setSocketTimeout(30000).setCookieSpec(CookieSpecs.IGNORE_COOKIES).setRedirectsEnabled(true); httpGet.setConfig(builder.build()); if (StringUtils.isNotBlank(cookies)) { httpGet.setHeader("Cookie", cookies); } httpGet.addHeader("Accept", "*/*"); httpGet.addHeader("Accept-Encoding", "gzip, deflate"); httpGet.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36"); if (requestProperties != null) { for (Map.Entry<String, String> entry : requestProperties.entrySet()) { httpGet.setHeader(entry.getKey(), entry.getValue()); } } try { return client.execute(httpGet, context); } catch (IllegalStateException e) { initClient(); throw e; } }
Example 2
Source File: SiteToSiteRestApiClient.java From nifi with Apache License 2.0 | 6 votes |
private void setupRequestConfig() { final RequestConfig.Builder requestConfigBuilder = RequestConfig.custom() .setConnectionRequestTimeout(connectTimeoutMillis) .setConnectTimeout(connectTimeoutMillis) .setSocketTimeout(readTimeoutMillis); if (localAddress != null) { requestConfigBuilder.setLocalAddress(localAddress); } if (proxy != null) { requestConfigBuilder.setProxy(proxy.getHttpHost()); } requestConfig = requestConfigBuilder.build(); }
Example 3
Source File: HttpComponentsClientHttpRequestFactory.java From spring4-understanding with Apache License 2.0 | 6 votes |
/** * Merge the given {@link HttpClient}-level {@link RequestConfig} with * the factory-level {@link RequestConfig}, if necessary. * @param clientConfig the config held by the current * @return the merged request config * (may be {@code null} if the given client config is {@code null}) * @since 4.2 */ protected RequestConfig mergeRequestConfig(RequestConfig clientConfig) { if (this.requestConfig == null) { // nothing to merge return clientConfig; } RequestConfig.Builder builder = RequestConfig.copy(clientConfig); int connectTimeout = this.requestConfig.getConnectTimeout(); if (connectTimeout >= 0) { builder.setConnectTimeout(connectTimeout); } int connectionRequestTimeout = this.requestConfig.getConnectionRequestTimeout(); if (connectionRequestTimeout >= 0) { builder.setConnectionRequestTimeout(connectionRequestTimeout); } int socketTimeout = this.requestConfig.getSocketTimeout(); if (socketTimeout >= 0) { builder.setSocketTimeout(socketTimeout); } return builder.build(); }
Example 4
Source File: PlaylistFactory.java From hlsparserj with Apache License 2.0 | 6 votes |
/** * Factory method to generate playlist object. This method uses a very * simple HTTP client to download the URL passed by the playlistURL * parameters. This method should not be used for applications that require * high-performance, as the HTTP connection management is very basic. If * your application has high performance requirements us the parsePlaylist * method that takes an InputStream. * * @param playlistVersion version of the playlist (V12 is the default) * @param playlistURL URL pointing to a playlist * @param connectTimeout timeout (ms) until a connection with the server is established * @param requestTimeout timeout (ms) used when requesting a connection from the connection manager * @param socketTimeout timeout (ms) waiting for data or a max period inactivity between 2 consecutive data packets * @return parsed playlist * @throws IOException on connection and parsing exceptions */ public static AbstractPlaylist parsePlaylist(final PlaylistVersion playlistVersion, final URL playlistURL, final int connectTimeout, final int requestTimeout, final int socketTimeout) throws IOException { RequestConfig.Builder requestBuilder = RequestConfig.custom(); requestBuilder = requestBuilder.setConnectTimeout(connectTimeout); requestBuilder = requestBuilder.setConnectionRequestTimeout(requestTimeout); requestBuilder = requestBuilder.setSocketTimeout(socketTimeout); final HttpClientBuilder builder = HttpClientBuilder.create(); builder.setDefaultRequestConfig(requestBuilder.build()); final CloseableHttpClient httpClient = builder.build(); final PlaylistParser parser = new PlaylistParser(); try { final InputStream playlistStream = getPlaylistInputStream(httpClient, playlistURL); parser.parse(playlistStream); } finally { httpClient.close(); } return getVersionSpecificPlaylist(parser, playlistVersion); }
Example 5
Source File: HttpClientManager.java From pentaho-kettle with Apache License 2.0 | 6 votes |
public CloseableHttpClient build() { HttpClientBuilder httpClientBuilder = HttpClientBuilder.create(); httpClientBuilder.setConnectionManager( manager ); RequestConfig.Builder requestConfigBuilder = RequestConfig.custom(); if ( socketTimeout > 0 ) { requestConfigBuilder.setSocketTimeout( socketTimeout ); } if ( connectionTimeout > 0 ) { requestConfigBuilder.setConnectTimeout( socketTimeout ); } if ( proxy != null ) { requestConfigBuilder.setProxy( proxy ); } httpClientBuilder.setDefaultRequestConfig( requestConfigBuilder.build() ); if ( provider != null ) { httpClientBuilder.setDefaultCredentialsProvider( provider ); } if ( redirectStrategy != null ) { httpClientBuilder.setRedirectStrategy( redirectStrategy ); } return httpClientBuilder.build(); }
Example 6
Source File: LogSender.java From desktop with GNU General Public License v3.0 | 6 votes |
public boolean send(File compressedLog) throws IOException { boolean success = true; HttpClient client = HttpClientBuilder.create().build(); HttpPut request = new HttpPut(serverURL+"?type=compress"); request.addHeader("computer", config.getDeviceName()); // Set request parameters RequestConfig.Builder reqConf = RequestConfig.custom(); reqConf.setSocketTimeout(2000); reqConf.setConnectTimeout(1000); request.setConfig(reqConf.build()); setRequest(request, compressedLog); HttpResponse response = client.execute(request); int responseCode = response.getStatusLine().getStatusCode(); if (responseCode != 201) { success = false; } return success; }
Example 7
Source File: PiwikTracker.java From matomo-java-tracker with BSD 3-Clause "New" or "Revised" License | 6 votes |
/** * Get an async HTTP client. With proxy if a proxy is provided in the constructor. * @return an async HTTP client */ protected CloseableHttpAsyncClient getHttpAsyncClient(){ HttpAsyncClientBuilder builder = HttpAsyncClientBuilder.create(); if(proxyHost != null && proxyPort != 0) { HttpHost proxy = new HttpHost(proxyHost, proxyPort); DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy); builder.setRoutePlanner(routePlanner); } RequestConfig.Builder config = RequestConfig.custom() .setConnectTimeout(timeout) .setConnectionRequestTimeout(timeout) .setSocketTimeout(timeout); builder.setDefaultRequestConfig(config.build()); return builder.build(); }
Example 8
Source File: ApacheHttpClient43EngineWithRetry.java From pnc with Apache License 2.0 | 5 votes |
@Override protected HttpClient createDefaultHttpClient() { logger.info("Bootstrapping http engine with request retry handler..."); final HttpClientBuilder builder = HttpClientBuilder.create(); RequestConfig.Builder requestBuilder = RequestConfig.custom(); if (defaultProxy != null) { requestBuilder.setProxy(defaultProxy); } builder.disableContentCompression(); builder.setDefaultRequestConfig(requestBuilder.build()); HttpRequestRetryHandler retryHandler = new StandardHttpRequestRetryHandler(); builder.setRetryHandler(retryHandler); return builder.build(); }
Example 9
Source File: GoogleTranslator.java From AndroidLocalizePlugin with Apache License 2.0 | 5 votes |
@Override public String query() throws Exception { URIBuilder uri = new URIBuilder(url); for (String key : formData.keySet()) { String value = formData.get(key); uri.addParameter(key, value); } HttpGet request = new HttpGet(uri.toString()); RequestConfig.Builder builder = RequestConfig.copy(RequestConfig.DEFAULT) .setSocketTimeout(5000) .setConnectTimeout(5000) .setConnectionRequestTimeout(5000); if (PluginConfig.isEnableProxy()) { HttpHost proxy = new HttpHost(PluginConfig.getHostName(), PluginConfig.getPortNumber()); builder.setProxy(proxy); } RequestConfig config = builder.build(); request.setConfig(config); CloseableHttpResponse response = httpClient.execute(request); HttpEntity entity = response.getEntity(); String result = EntityUtils.toString(entity, "UTF-8"); EntityUtils.consume(entity); response.getEntity().getContent().close(); response.close(); return result; }
Example 10
Source File: HttpManager.java From PicCrawler with Apache License 2.0 | 5 votes |
/** * 获取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(); }
Example 11
Source File: WebServiceClient.java From GeoIP2-java with Apache License 2.0 | 5 votes |
private WebServiceClient(Builder builder) { this.host = builder.host; this.port = builder.port; this.useHttps = builder.useHttps; this.locales = builder.locales; this.licenseKey = builder.licenseKey; this.accountId = builder.accountId; mapper = new ObjectMapper(); mapper.disable(MapperFeature.CAN_OVERRIDE_ACCESS_MODIFIERS); mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); RequestConfig.Builder configBuilder = RequestConfig.custom() .setConnectTimeout(builder.connectTimeout) .setSocketTimeout(builder.readTimeout); if (builder.proxy != null && builder.proxy != Proxy.NO_PROXY) { InetSocketAddress address = (InetSocketAddress) builder.proxy.address(); HttpHost proxyHost = new HttpHost(address.getHostName(), address.getPort()); configBuilder.setProxy(proxyHost); } RequestConfig config = configBuilder.build(); httpClient = HttpClientBuilder.create() .setUserAgent(userAgent()) .setDefaultRequestConfig(config).build(); }
Example 12
Source File: StandardMattermostService.java From jenkins-mattermost-plugin with MIT License | 5 votes |
private RequestConfig.Builder setupProxy(ProxyConfiguration proxy, HttpClientBuilder clientBuilder, RequestConfig.Builder reqconfigconbuilder) throws MalformedURLException { HttpHost proxyHost = new HttpHost(proxy.name, proxy.port); DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxyHost); clientBuilder.setRoutePlanner(routePlanner); reqconfigconbuilder.setProxy(proxyHost); setupProxyAuth(proxy, clientBuilder, proxyHost); return reqconfigconbuilder; }
Example 13
Source File: MixerHttpClient.java From beam-client-java with MIT License | 5 votes |
/** * Creates a {@link org.apache.http.HttpRequest} given a type, path, and optional content. * * @param requestType The type of HTTP/1.1 request to make (see {@link RequestType} * for more details. * @param uri The URI to request content from. * @param args The content of the request. This parameter is optional and considered to be nullable. * * @return A request built from the specification above. */ private HttpUriRequest makeRequest(RequestType requestType, URI uri, Object... args) { RequestConfig.Builder config = RequestConfig.copy(RequestConfig.DEFAULT); config.setCookieSpec(CookieSpecs.BEST_MATCH); RequestBuilder requestBuilder = RequestBuilder.create(requestType.name()) .setUri(uri) .setConfig(config.build()) .setEntity(this.makeEntity(args)) .setHeader("User-Agent", this.getUserAgent()); if (this.oauthToken != null) { requestBuilder.addHeader("Authorization", "Bearer " + this.oauthToken); } if (this.jwt != null) { requestBuilder.addHeader("Authorization", "JWT " + this.jwtString); } if (this.oauthToken == null && this.jwt == null) { requestBuilder.addHeader("Client-Id", clientId); } if (this.csrfToken != null) { requestBuilder.addHeader(CSRF_TOKEN_HEADER, this.csrfToken); } return requestBuilder.build(); }
Example 14
Source File: EndPointClient.java From appengine-tck with Apache License 2.0 | 5 votes |
/** * Get client. * * @return the client */ private synchronized CloseableHttpClient getClient() { if (client == null) { RequestConfig.Builder requestBuilder = RequestConfig.custom(); requestBuilder.setConnectTimeout(connectionTimeout); ConnectionConfig.Builder connBuilder = ConnectionConfig.custom(); connBuilder.setCharset(Charset.forName(getContentCharset())); // Create and initialize scheme registry RegistryBuilder<ConnectionSocketFactory> builder = RegistryBuilder.create(); builder.register("http", getPlainFactory()); builder.register("https", getSslFactory()); Registry<ConnectionSocketFactory> registry = builder.build(); HttpClientConnectionManager hccm = createClientConnectionManager(registry); HttpClientBuilder clientBuilder = HttpClients.custom(); clientBuilder.setDefaultRequestConfig(requestBuilder.build()); clientBuilder.setDefaultConnectionConfig(connBuilder.build()); clientBuilder.setConnectionManager(hccm); client = clientBuilder.build(); } return client; }
Example 15
Source File: ClientHttpRequestFactoryFactory.java From spring-credhub with Apache License 2.0 | 5 votes |
static ClientHttpRequestFactory usingHttpComponents(ClientOptions options) throws GeneralSecurityException { HttpClientBuilder httpClientBuilder = HttpClients.custom(); if (usingCustomCerts(options)) { SSLContext sslContext = sslCertificateUtils.getSSLContext(options.getCaCertFiles()); SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext); httpClientBuilder.setSSLSocketFactory(sslSocketFactory).setSSLContext(sslContext); } else { httpClientBuilder.setSSLContext(SSLContext.getDefault()).useSystemProperties(); } RequestConfig.Builder requestConfigBuilder = RequestConfig.custom().setAuthenticationEnabled(true); if (options.getConnectionTimeout() != null) { requestConfigBuilder.setConnectTimeout(options.getConnectionTimeoutMillis()); } if (options.getReadTimeout() != null) { requestConfigBuilder.setSocketTimeout(options.getReadTimeoutMillis()); } httpClientBuilder.setDefaultRequestConfig(requestConfigBuilder.build()); return new HttpComponentsClientHttpRequestFactory(httpClientBuilder.build()); }
Example 16
Source File: ApacheHttpRequestFactory.java From aws-sdk-java-v2 with Apache License 2.0 | 5 votes |
private void addRequestConfig(final HttpRequestBase base, final SdkHttpRequest request, final ApacheHttpRequestConfig requestConfig) { int connectTimeout = saturatedCast(requestConfig.connectionTimeout().toMillis()); int connectAcquireTimeout = saturatedCast(requestConfig.connectionAcquireTimeout().toMillis()); RequestConfig.Builder requestConfigBuilder = RequestConfig .custom() .setConnectionRequestTimeout(connectAcquireTimeout) .setConnectTimeout(connectTimeout) .setSocketTimeout(saturatedCast(requestConfig.socketTimeout().toMillis())) .setLocalAddress(requestConfig.localAddress()); ApacheUtils.disableNormalizeUri(requestConfigBuilder); /* * Enable 100-continue support for PUT operations, since this is * where we're potentially uploading large amounts of data and want * to find out as early as possible if an operation will fail. We * don't want to do this for all operations since it will cause * extra latency in the network interaction. */ if (SdkHttpMethod.PUT == request.method() && requestConfig.expectContinueEnabled()) { requestConfigBuilder.setExpectContinueEnabled(true); } base.setConfig(requestConfigBuilder.build()); }
Example 17
Source File: HttpWebhookSender.java From openvidu with Apache License 2.0 | 5 votes |
public HttpWebhookSender(String httpEndpoint, List<Header> headers, List<CDREventName> events) { this.httpEndpoint = httpEndpoint; this.events = events; this.customHeaders = new ArrayList<>(); boolean contentTypeHeaderAdded = false; for (Header header : headers) { this.customHeaders.add(header); if (!contentTypeHeaderAdded && HttpHeaders.CONTENT_TYPE.equals(header.getName()) && "application/json".equals(header.getValue())) { contentTypeHeaderAdded = true; } } if (!contentTypeHeaderAdded) { this.customHeaders.add(new BasicHeader(HttpHeaders.CONTENT_TYPE, "application/json")); } TrustStrategy trustStrategy = new TrustStrategy() { @Override public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException { return true; } }; SSLContext sslContext; try { sslContext = new SSLContextBuilder().loadTrustMaterial(null, trustStrategy).build(); } catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) { throw new RuntimeException(e); } RequestConfig.Builder requestBuilder = RequestConfig.custom(); requestBuilder = requestBuilder.setConnectTimeout(30000); requestBuilder = requestBuilder.setConnectionRequestTimeout(30000); this.httpClient = HttpClientBuilder.create().setDefaultRequestConfig(requestBuilder.build()) .setConnectionTimeToLive(30, TimeUnit.SECONDS).setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE) .setSSLContext(sslContext).build(); }
Example 18
Source File: HttpClientUtils.java From train-ticket-reaper with MIT License | 4 votes |
public static String doGet(String url, Map<String, String> param, Map<String, String> headers, String charset, String proxyHost, Integer proxyPort) { // 创建Http请求配置参数 RequestConfig.Builder requestBuilder = RequestConfig.custom() // 获取连接超时时间 .setConnectionRequestTimeout(10000) // 请求超时时间 .setConnectTimeout(10000) // 响应超时时间 .setSocketTimeout(10000); HttpHost httpHost = null; if (proxyHost != null && proxyPort != null) { httpHost = new HttpHost(proxyHost, proxyPort); requestBuilder.setProxy(httpHost); } RequestConfig requestConfig = requestBuilder.build(); // 创建httpClient HttpClientBuilder httpClientBuilder = HttpClients.custom(); httpClientBuilder // 把请求相关的超时信息设置到连接客户端 .setDefaultRequestConfig(requestConfig) // 把请求重试设置到连接客户端 .setRetryHandler(new RetryHandler()); CloseableHttpClient httpClient = httpClientBuilder.build(); HttpClientContext httpClientContext = HttpClientContext.create(); CloseableHttpResponse response = null; String resultString = ""; try { // 创建uri URIBuilder builder = new URIBuilder(url); if (param != null) { for (String key : param.keySet()) { builder.addParameter(key, param.get(key)); } } URI uri = builder.build(); // 创建http GET请求 HttpGet httpGet = new HttpGet(uri); //请求头 setHeaders(headers, httpGet); // 执行请求 response = httpClient.execute(httpGet); // 判断返回状态是否为200 if (response.getStatusLine().getStatusCode() == 200) { resultString = EntityUtils.toString(response.getEntity(), charset); } } catch (Exception e) { e.printStackTrace(); } finally { closeResponse(httpClient, response); } return resultString; }
Example 19
Source File: HttpClientFactory.java From hsac-fitnesse-fixtures with Apache License 2.0 | 4 votes |
public void setRequestConfigBuilder(RequestConfig.Builder requestConfigBuilder) { this.requestConfigBuilder = requestConfigBuilder; }
Example 20
Source File: HttpClientFactory.java From hsac-fitnesse-fixtures with Apache License 2.0 | 4 votes |
public RequestConfig.Builder getRequestConfigBuilder() { return requestConfigBuilder; }