List of usage examples for org.apache.http.impl.client DefaultHttpRequestRetryHandler DefaultHttpRequestRetryHandler
@SuppressWarnings("unchecked") public DefaultHttpRequestRetryHandler(final int retryCount, final boolean requestSentRetryEnabled)
From source file:com.miapc.ipudong.Application.java
@Bean public RestTemplate getRestTemplate() { SSLContext sslcontext = null; Set<KeyManager> keymanagers = new LinkedHashSet<>(); Set<TrustManager> trustmanagers = new LinkedHashSet<>(); try {/*from w ww . j a v a2 s . c o m*/ trustmanagers.add(new HttpsTrustManager()); KeyManager[] km = keymanagers.toArray(new KeyManager[keymanagers.size()]); TrustManager[] tm = trustmanagers.toArray(new TrustManager[trustmanagers.size()]); sslcontext = SSLContexts.custom().build(); sslcontext.init(km, tm, new SecureRandom()); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (KeyManagementException e) { e.printStackTrace(); } SSLConnectionSocketFactory factory = new SSLConnectionSocketFactory(sslcontext, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER); HttpClientBuilder httpClientBuilder = HttpClients.custom(); httpClientBuilder.setSSLSocketFactory(factory); // ?3? httpClientBuilder.setRetryHandler(new DefaultHttpRequestRetryHandler(2, true)); // ????Keep-Alive httpClientBuilder.setKeepAliveStrategy(new DefaultConnectionKeepAliveStrategy()); 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")); headers.add(new BasicHeader("Authorization", "reslibu")); httpClientBuilder.setDefaultHeaders(headers); CloseableHttpClient httpClient = httpClientBuilder.build(); if (httpClient != null) { // httpClient??RequestConfig HttpComponentsClientHttpRequestFactory clientHttpRequestFactory = new HttpComponentsClientHttpRequestFactory( httpClient); // clientHttpRequestFactory.setConnectTimeout(60 * 1000); // ???SocketTimeout clientHttpRequestFactory.setReadTimeout(5 * 60 * 1000); // ???? clientHttpRequestFactory.setConnectionRequestTimeout(5000); // ?truePOSTPUT????false? // clientHttpRequestFactory.setBufferRequestBody(false); // ? List<HttpMessageConverter<?>> messageConverters = new ArrayList<>(); messageConverters.add(new StringHttpMessageConverter(Charset.forName("UTF-8"))); messageConverters.add(new MappingJackson2HttpMessageConverter()); messageConverters.add(new FormHttpMessageConverter()); messageConverters.add(new MappingJackson2XmlHttpMessageConverter()); RestTemplate restTemplate = new RestTemplate(messageConverters); restTemplate.setRequestFactory(clientHttpRequestFactory); restTemplate.setErrorHandler(new DefaultResponseErrorHandler()); return restTemplate; } else { return null; } }
From source file:org.frontcache.client.FrontCacheClient.java
private FrontCacheClient(String frontcacheURL) { final RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(CONNECTION_TIMEOUT) .setConnectTimeout(CONNECTION_TIMEOUT).setCookieSpec(CookieSpecs.IGNORE_COOKIES).build(); ConnectionKeepAliveStrategy keepAliveStrategy = new ConnectionKeepAliveStrategy() { @Override/*from w w w. j av a2s . c o m*/ 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")) { return Long.parseLong(value) * 1000; } } return 10 * 1000; } }; client = HttpClients.custom().setDefaultRequestConfig(requestConfig) .setRetryHandler(new DefaultHttpRequestRetryHandler(0, false)) .setKeepAliveStrategy(keepAliveStrategy).setRedirectStrategy(new RedirectStrategy() { @Override public boolean isRedirected(HttpRequest request, HttpResponse response, HttpContext context) throws ProtocolException { return false; } @Override public HttpUriRequest getRedirect(HttpRequest request, HttpResponse response, HttpContext context) throws ProtocolException { return null; } }).build(); this.frontCacheURL = frontcacheURL; if (frontcacheURL.endsWith("/")) this.frontCacheURI = frontcacheURL + IO_URI; else this.frontCacheURI = frontcacheURL + "/" + IO_URI; }
From source file:ee.ria.xroad.proxy.clientproxy.FastestConnectionSelectingSSLSocketFactoryIntegrationTest.java
private static void createClient() throws Exception { RegistryBuilder<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder .<ConnectionSocketFactory>create(); socketFactoryRegistry.register("http", PlainConnectionSocketFactory.INSTANCE); socketFactoryRegistry.register("https", createSSLSocketFactory()); PoolingHttpClientConnectionManager connMgr = new PoolingHttpClientConnectionManager( socketFactoryRegistry.build()); connMgr.setMaxTotal(CLIENT_MAX_TOTAL_CONNECTIONS); connMgr.setDefaultMaxPerRoute(CLIENT_MAX_CONNECTIONS_PER_ROUTE); int timeout = SystemProperties.getClientProxyTimeout(); RequestConfig.Builder rb = RequestConfig.custom(); rb.setConnectTimeout(timeout);//from www. ja va2s.c om rb.setConnectionRequestTimeout(timeout); rb.setSocketTimeout(timeout); HttpClientBuilder cb = HttpClients.custom(); cb.setConnectionManager(connMgr); cb.setDefaultRequestConfig(rb.build()); // Disable request retry cb.setRetryHandler(new DefaultHttpRequestRetryHandler(0, false)); client = cb.build(); }
From source file:jetbrains.teamcilty.github.api.impl.HttpClientWrapperImpl.java
public HttpClientWrapperImpl() throws UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException { final String serverVersion = ServerVersionHolder.getVersion().getDisplayVersion(); final HttpParams ps = new BasicHttpParams(); DefaultHttpClient.setDefaultHttpParams(ps); final int timeout = TeamCityProperties.getInteger("teamcity.github.http.timeout", 300 * 1000); HttpConnectionParams.setConnectionTimeout(ps, timeout); HttpConnectionParams.setSoTimeout(ps, timeout); HttpProtocolParams.setUserAgent(ps, "JetBrains TeamCity " + serverVersion); final SchemeRegistry schemaRegistry = SchemeRegistryFactory.createDefault(); final SSLSocketFactory sslSocketFactory = new SSLSocketFactory(new TrustStrategy() { public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException { return !TeamCityProperties.getBoolean("teamcity.github.verify.ssl.certificate"); }/*from w ww . jav a 2 s .c om*/ }); schemaRegistry.register(new Scheme("https", 443, sslSocketFactory)); final DefaultHttpClient httpclient = new DefaultHttpClient(new ThreadSafeClientConnManager(schemaRegistry), ps); setupProxy(httpclient); httpclient.setRoutePlanner(new ProxySelectorRoutePlanner( httpclient.getConnectionManager().getSchemeRegistry(), ProxySelector.getDefault())); httpclient.addRequestInterceptor(new RequestAcceptEncoding()); httpclient.addResponseInterceptor(new ResponseContentEncoding()); httpclient.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler(3, true)); myClient = httpclient; }
From source file:org.jfrog.build.client.PreemptiveHttpClient.java
private DefaultHttpClient createHttpClient(String userName, String password, int timeout) { BasicHttpParams params = new BasicHttpParams(); int timeoutMilliSeconds = timeout * 1000; HttpConnectionParams.setConnectionTimeout(params, timeoutMilliSeconds); HttpConnectionParams.setSoTimeout(params, timeoutMilliSeconds); DefaultHttpClient client = new DefaultHttpClient(params); if (userName != null && !"".equals(userName)) { client.getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), new UsernamePasswordCredentials(userName, password)); localContext = new BasicHttpContext(); // Generate BASIC scheme object and stick it to the local execution context BasicScheme basicAuth = new BasicScheme(); localContext.setAttribute("preemptive-auth", basicAuth); // Add as the first request interceptor client.addRequestInterceptor(new PreemptiveAuth(), 0); }/*w w w. j av a 2s . c o m*/ boolean requestSentRetryEnabled = Boolean.parseBoolean(System.getProperty("requestSentRetryEnabled")); if (requestSentRetryEnabled) { client.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler(3, requestSentRetryEnabled)); } // set the following user agent with each request String userAgent = "ArtifactoryBuildClient/" + CLIENT_VERSION; HttpProtocolParams.setUserAgent(client.getParams(), userAgent); return client; }
From source file:com.cloudbees.plugins.binarydeployer.http.HttpRepository.java
@Override protected void deploy(List<Binary> binaries, Run run) throws IOException { CloseableHttpClient client = null;/* w ww . java2 s .c o m*/ try { if (credentialsId == null || credentialsId.isEmpty()) { client = HttpClients.createDefault(); } else { BasicCredentialsProvider credentials = new BasicCredentialsProvider(); StandardUsernamePasswordCredentials credentialById = CredentialsProvider.findCredentialById( credentialsId, StandardUsernamePasswordCredentials.class, run, Lists.<DomainRequirement>newArrayList()); credentials.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials( credentialById.getUsername(), credentialById.getPassword().getPlainText())); client = HttpClients.custom().setDefaultCredentialsProvider(credentials).disableAutomaticRetries() .setRetryHandler(new DefaultHttpRequestRetryHandler(0, false)).build(); } for (Binary binary : binaries) { BufferedHttpEntity entity = new BufferedHttpEntity( new InputStreamEntity(binary.getFile().open(), binary.getFile().length())); HttpPost post = new HttpPost(remoteLocation + binary.getName()); post.setEntity(entity); CloseableHttpResponse response = null; try { response = client.execute(post); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode >= 200 && statusCode < 300) { log.fine("Deployed " + binary.getName() + " to " + remoteLocation); } else { log.warning("Cannot deploy file " + binary.getName() + ". Response from target was " + statusCode); run.setResult(Result.FAILURE); throw new IOException(response.getStatusLine().toString()); } } finally { if (response != null) { response.close(); } } } } finally { if (client != null) { client.close(); } } }
From source file:ee.ria.xroad.common.opmonitoring.OpMonitoringDaemonHttpClient.java
/** * Creates HTTP client.// w ww . j ava2 s. co m * @param authKey the client's authentication key * @param clientMaxTotalConnections client max total connections * @param clientMaxConnectionsPerRoute client max connections per route * @param connectionTimeoutMilliseconds connection timeout in milliseconds * @param socketTimeoutMilliseconds socket timeout in milliseconds * @return HTTP client * @throws Exception if creating a HTTPS client and SSLContext * initialization fails */ public static CloseableHttpClient createHttpClient(InternalSSLKey authKey, int clientMaxTotalConnections, int clientMaxConnectionsPerRoute, int connectionTimeoutMilliseconds, int socketTimeoutMilliseconds) throws Exception { log.trace("createHttpClient()"); RegistryBuilder<ConnectionSocketFactory> sfr = RegistryBuilder.<ConnectionSocketFactory>create(); if ("https".equalsIgnoreCase(OpMonitoringSystemProperties.getOpMonitorDaemonScheme())) { sfr.register("https", createSSLSocketFactory(authKey)); } else { sfr.register("http", PlainConnectionSocketFactory.INSTANCE); } PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(sfr.build()); cm.setMaxTotal(clientMaxTotalConnections); cm.setDefaultMaxPerRoute(clientMaxConnectionsPerRoute); cm.setDefaultSocketConfig(SocketConfig.custom().setTcpNoDelay(true).build()); RequestConfig.Builder rb = RequestConfig.custom().setConnectTimeout(connectionTimeoutMilliseconds) .setConnectionRequestTimeout(connectionTimeoutMilliseconds) .setSocketTimeout(socketTimeoutMilliseconds); HttpClientBuilder cb = HttpClients.custom().setConnectionManager(cm).setDefaultRequestConfig(rb.build()); // Disable request retry cb.setRetryHandler(new DefaultHttpRequestRetryHandler(0, false)); return cb.build(); }
From source file:org.jupnp.transport.impl.apache.StreamClientImpl.java
public StreamClientImpl(StreamClientConfigurationImpl configuration) throws InitializationException { this.configuration = configuration; HttpProtocolParams.setContentCharset(globalParams, getConfiguration().getContentCharset()); HttpProtocolParams.setUseExpectContinue(globalParams, false); // These are some safety settings, we should never run into these timeouts as we // do our own expiration checking HttpConnectionParams.setConnectionTimeout(globalParams, (getConfiguration().getTimeoutSeconds() + 5) * 1000); HttpConnectionParams.setSoTimeout(globalParams, (getConfiguration().getTimeoutSeconds() + 5) * 1000); HttpConnectionParams.setStaleCheckingEnabled(globalParams, getConfiguration().getStaleCheckingEnabled()); if (getConfiguration().getSocketBufferSize() != -1) HttpConnectionParams.setSocketBufferSize(globalParams, getConfiguration().getSocketBufferSize()); // Only register 80, not 443 and SSL SchemeRegistry registry = new SchemeRegistry(); registry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory())); clientConnectionManager = new PoolingClientConnectionManager(registry); clientConnectionManager.setMaxTotal(getConfiguration().getMaxTotalConnections()); clientConnectionManager.setDefaultMaxPerRoute(getConfiguration().getMaxTotalPerRoute()); httpClient = new DefaultHttpClient(clientConnectionManager, globalParams); if (getConfiguration().getRequestRetryCount() != -1) { httpClient.setHttpRequestRetryHandler( new DefaultHttpRequestRetryHandler(getConfiguration().getRequestRetryCount(), false)); }//from ww w. j ava2 s . c om }
From source file:com.netscape.certsrv.client.PKIConnection.java
public PKIConnection(ClientConfig config) { this.config = config; // Register https scheme. Scheme scheme = new Scheme("https", 443, new JSSProtocolSocketFactory()); httpClient.getConnectionManager().getSchemeRegistry().register(scheme); // Don't retry operations. httpClient.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler(0, false)); if (config.getUsername() != null && config.getPassword() != null) { List<String> authPref = new ArrayList<String>(); authPref.add(AuthPolicy.BASIC);//from w w w . ja v a 2s . c om httpClient.getParams().setParameter(AuthPNames.PROXY_AUTH_PREF, authPref); httpClient.getCredentialsProvider().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(config.getUsername(), config.getPassword())); } httpClient.addRequestInterceptor(new HttpRequestInterceptor() { @Override public void process(HttpRequest request, HttpContext context) throws HttpException, IOException { requestCounter++; if (verbose) { System.out.println("HTTP request: " + request.getRequestLine()); for (Header header : request.getAllHeaders()) { System.out.println(" " + header.getName() + ": " + header.getValue()); } } if (output != null) { File file = new File(output, "http-request-" + requestCounter); storeRequest(file, request); } // Set the request parameter to follow redirections. HttpParams params = request.getParams(); if (params instanceof ClientParamsStack) { ClientParamsStack paramsStack = (ClientParamsStack) request.getParams(); params = paramsStack.getRequestParams(); } HttpClientParams.setRedirecting(params, true); } }); httpClient.addResponseInterceptor(new HttpResponseInterceptor() { @Override public void process(HttpResponse response, HttpContext context) throws HttpException, IOException { responseCounter++; if (verbose) { System.out.println("HTTP response: " + response.getStatusLine()); for (Header header : response.getAllHeaders()) { System.out.println(" " + header.getName() + ": " + header.getValue()); } } if (output != null) { File file = new File(output, "http-response-" + responseCounter); storeResponse(file, response); } } }); httpClient.setRedirectStrategy(new DefaultRedirectStrategy() { @Override public HttpUriRequest getRedirect(HttpRequest request, HttpResponse response, HttpContext context) throws ProtocolException { HttpUriRequest uriRequest = super.getRedirect(request, response, context); URI uri = uriRequest.getURI(); if (verbose) System.out.println("HTTP redirect: " + uri); // Redirect the original request to the new URI. RequestWrapper wrapper; if (request instanceof HttpEntityEnclosingRequest) { wrapper = new EntityEnclosingRequestWrapper((HttpEntityEnclosingRequest) request); } else { wrapper = new RequestWrapper(request); } wrapper.setURI(uri); return wrapper; } @Override public boolean isRedirected(HttpRequest request, HttpResponse response, HttpContext context) throws ProtocolException { // The default redirection policy does not redirect POST or PUT. // This overrides the policy to follow redirections for all HTTP methods. return response.getStatusLine().getStatusCode() == 302; } }); engine = new ApacheHttpClient4Engine(httpClient); resteasyClient = new ResteasyClientBuilder().httpEngine(engine).build(); resteasyClient.register(PKIRESTProvider.class); }