List of usage examples for org.apache.http.impl.client DefaultHttpClient setHttpRequestRetryHandler
public synchronized void setHttpRequestRetryHandler(final HttpRequestRetryHandler handler)
From source file:Main.java
public static DefaultHttpClient getDefaultHttpClient() { SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443)); HttpParams params = new BasicHttpParams(); ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(params, schemeRegistry); DefaultHttpClient defaultHttpClient = new DefaultHttpClient(cm, params); HttpConnectionParams.setSoTimeout(defaultHttpClient.getParams(), SOCKET_TIME_OUT); HttpConnectionParams.setConnectionTimeout(defaultHttpClient.getParams(), CONNECTION_TIME_OUT); defaultHttpClient.getParams().setIntParameter(ClientPNames.MAX_REDIRECTS, 10); HttpClientParams.setCookiePolicy(defaultHttpClient.getParams(), CookiePolicy.BROWSER_COMPATIBILITY); HttpProtocolParams.setUserAgent(defaultHttpClient.getParams(), "Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.9.2.18) Gecko/20110628 Ubuntu/10.04 (lucid) Firefox/3.6.18"); defaultHttpClient.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler(3, true)); return defaultHttpClient; }
From source file:org.jets3t.service.utils.RestUtils.java
public static HttpClient initHttpsConnection(final JetS3tRequestAuthorizer requestAuthorizer, Jets3tProperties jets3tProperties, String userAgentDescription, CredentialsProvider credentialsProvider) { // Configure HttpClient properties based on Jets3t Properties. HttpParams params = createDefaultHttpParams(); params.setParameter(Jets3tProperties.JETS3T_PROPERTIES_ID, jets3tProperties); params.setParameter(ClientPNames.CONNECTION_MANAGER_FACTORY_CLASS_NAME, jets3tProperties.getStringProperty( ClientPNames.CONNECTION_MANAGER_FACTORY_CLASS_NAME, ConnManagerFactory.class.getName())); HttpConnectionParams.setConnectionTimeout(params, jets3tProperties.getIntProperty("httpclient.connection-timeout-ms", 60000)); HttpConnectionParams.setSoTimeout(params, jets3tProperties.getIntProperty("httpclient.socket-timeout-ms", 60000)); HttpConnectionParams.setStaleCheckingEnabled(params, jets3tProperties.getBoolProperty("httpclient.stale-checking-enabled", true)); // Connection properties to take advantage of S3 window scaling. if (jets3tProperties.containsKey("httpclient.socket-receive-buffer")) { HttpConnectionParams.setSocketBufferSize(params, jets3tProperties.getIntProperty("httpclient.socket-receive-buffer", 0)); }//from w w w . jav a 2s .com HttpConnectionParams.setTcpNoDelay(params, true); // Set user agent string. String userAgent = jets3tProperties.getStringProperty("httpclient.useragent", null); if (userAgent == null) { userAgent = ServiceUtils.getUserAgentDescription(userAgentDescription); } if (log.isDebugEnabled()) { log.debug("Setting user agent string: " + userAgent); } HttpProtocolParams.setUserAgent(params, userAgent); boolean expectContinue = jets3tProperties.getBoolProperty("http.protocol.expect-continue", true); HttpProtocolParams.setUseExpectContinue(params, expectContinue); long connectionManagerTimeout = jets3tProperties.getLongProperty("httpclient.connection-manager-timeout", 0); ConnManagerParams.setTimeout(params, connectionManagerTimeout); DefaultHttpClient httpClient = wrapClient(params); httpClient.setHttpRequestRetryHandler(new JetS3tRetryHandler( jets3tProperties.getIntProperty("httpclient.retry-max", 5), requestAuthorizer)); if (credentialsProvider != null) { if (log.isDebugEnabled()) { log.debug("Using credentials provider class: " + credentialsProvider.getClass().getName()); } httpClient.setCredentialsProvider(credentialsProvider); if (jets3tProperties.getBoolProperty("httpclient.authentication-preemptive", false)) { // Add as the very first interceptor in the protocol chain httpClient.addRequestInterceptor(new PreemptiveInterceptor(), 0); } } return httpClient; }
From source file:org.jets3t.service.utils.RestUtils.java
/** * Initialises, or re-initialises, the underlying HttpConnectionManager and * HttpClient objects a service will use to communicate with an AWS service. * If proxy settings are specified in this service's {@link Jets3tProperties} object, * these settings will also be passed on to the underlying objects. *///from w ww . j a v a 2 s .co m public static HttpClient initHttpConnection(final JetS3tRequestAuthorizer requestAuthorizer, Jets3tProperties jets3tProperties, String userAgentDescription, CredentialsProvider credentialsProvider) { // Configure HttpClient properties based on Jets3t Properties. HttpParams params = createDefaultHttpParams(); params.setParameter(Jets3tProperties.JETS3T_PROPERTIES_ID, jets3tProperties); params.setParameter(ClientPNames.CONNECTION_MANAGER_FACTORY_CLASS_NAME, jets3tProperties.getStringProperty( ClientPNames.CONNECTION_MANAGER_FACTORY_CLASS_NAME, ConnManagerFactory.class.getName())); HttpConnectionParams.setConnectionTimeout(params, jets3tProperties.getIntProperty("httpclient.connection-timeout-ms", 60000)); HttpConnectionParams.setSoTimeout(params, jets3tProperties.getIntProperty("httpclient.socket-timeout-ms", 60000)); HttpConnectionParams.setStaleCheckingEnabled(params, jets3tProperties.getBoolProperty("httpclient.stale-checking-enabled", true)); // Connection properties to take advantage of S3 window scaling. if (jets3tProperties.containsKey("httpclient.socket-receive-buffer")) { HttpConnectionParams.setSocketBufferSize(params, jets3tProperties.getIntProperty("httpclient.socket-receive-buffer", 0)); } HttpConnectionParams.setTcpNoDelay(params, true); // Set user agent string. String userAgent = jets3tProperties.getStringProperty("httpclient.useragent", null); if (userAgent == null) { userAgent = ServiceUtils.getUserAgentDescription(userAgentDescription); } if (log.isDebugEnabled()) { log.debug("Setting user agent string: " + userAgent); } HttpProtocolParams.setUserAgent(params, userAgent); boolean expectContinue = jets3tProperties.getBoolProperty("http.protocol.expect-continue", true); HttpProtocolParams.setUseExpectContinue(params, expectContinue); long connectionManagerTimeout = jets3tProperties.getLongProperty("httpclient.connection-manager-timeout", 0); ConnManagerParams.setTimeout(params, connectionManagerTimeout); DefaultHttpClient httpClient = new DefaultHttpClient(params); httpClient.setHttpRequestRetryHandler(new JetS3tRetryHandler( jets3tProperties.getIntProperty("httpclient.retry-max", 5), requestAuthorizer)); if (credentialsProvider != null) { if (log.isDebugEnabled()) { log.debug("Using credentials provider class: " + credentialsProvider.getClass().getName()); } httpClient.setCredentialsProvider(credentialsProvider); if (jets3tProperties.getBoolProperty("httpclient.authentication-preemptive", false)) { // Add as the very first interceptor in the protocol chain httpClient.addRequestInterceptor(new PreemptiveInterceptor(), 0); } } return httpClient; }
From source file:com.mobicage.rogerthat.util.http.HTTPUtil.java
public static HttpClient getHttpClient(int connectionTimeout, int socketTimeout, final int retryCount) { final HttpParams params = new BasicHttpParams(); HttpConnectionParams.setStaleCheckingEnabled(params, true); HttpConnectionParams.setConnectionTimeout(params, connectionTimeout); HttpConnectionParams.setSoTimeout(params, socketTimeout); HttpClientParams.setRedirecting(params, false); final DefaultHttpClient httpClient = new DefaultHttpClient(params); if (shouldUseTruststore()) { KeyStore trustStore = loadTrustStore(); SSLSocketFactory socketFactory; try {//from ww w. j ava 2s . com socketFactory = new SSLSocketFactory(null, null, trustStore); } catch (Exception e) { throw new RuntimeException(e); } socketFactory.setHostnameVerifier(SSLSocketFactory.STRICT_HOSTNAME_VERIFIER); Scheme sch = new Scheme("https", socketFactory, CloudConstants.HTTPS_PORT); httpClient.getConnectionManager().getSchemeRegistry().register(sch); } if (retryCount > 0) { httpClient.setHttpRequestRetryHandler(new HttpRequestRetryHandler() { @Override public boolean retryRequest(IOException exception, int executionCount, HttpContext context) { return executionCount < retryCount; } }); } return httpClient; }
From source file:org.jboss.as.test.integration.management.interfaces.HttpManagementInterface.java
private static HttpClient createHttpClient(String host, int port, String username, String password) { PoolingClientConnectionManager connectionPool = new PoolingClientConnectionManager(); DefaultHttpClient httpClient = new DefaultHttpClient(connectionPool); SchemeRegistry schemeRegistry = httpClient.getConnectionManager().getSchemeRegistry(); schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory())); try {//from w ww .j a v a2 s. c o m schemeRegistry.register(new Scheme("https", 443, new SSLSocketFactory(new TrustStrategy() { @Override public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException { return true; } }, new AllowAllHostnameVerifier()))); } catch (Exception e) { throw new RuntimeException(e); } httpClient.setHttpRequestRetryHandler(new StandardHttpRequestRetryHandler(5, true)); httpClient.getCredentialsProvider().setCredentials( new AuthScope(host, port, MANAGEMENT_REALM, AuthPolicy.DIGEST), new UsernamePasswordCredentials(username, password)); return httpClient; }
From source file:com.futureplatforms.kirin.internal.attic.IOUtils.java
public static HttpClient newHttpClient() { int timeout = 3 * 60 * 1000; DefaultHttpClient httpClient = new DefaultHttpClient(); ClientConnectionManager mgr = httpClient.getConnectionManager(); HttpParams params = httpClient.getParams(); ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(params, mgr.getSchemeRegistry()); httpClient = new DefaultHttpClient(cm, params); // how long are we prepared to wait to establish a connection? HttpConnectionParams.setConnectionTimeout(params, timeout); // how long should the socket wait for data? HttpConnectionParams.setSoTimeout(params, timeout); httpClient.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler(3, false) { @Override//from w ww. j a va 2s . co m public boolean retryRequest(IOException exception, int executionCount, HttpContext context) { return super.retryRequest(exception, executionCount, context); } @Override public boolean isRequestSentRetryEnabled() { return false; } }); httpClient.addRequestInterceptor(new HttpRequestInterceptor() { public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException { if (!request.containsHeader("Accept-Encoding")) { request.addHeader("Accept-Encoding", "gzip"); } } }); httpClient.addResponseInterceptor(new HttpResponseInterceptor() { public void process(final HttpResponse response, final HttpContext context) throws HttpException, IOException { response.removeHeaders("Set-Cookie"); HttpEntity entity = response.getEntity(); Header contentEncodingHeader = entity.getContentEncoding(); if (contentEncodingHeader != null) { HeaderElement[] codecs = contentEncodingHeader.getElements(); for (int i = 0; i < codecs.length; i++) { if (codecs[i].getName().equalsIgnoreCase("gzip")) { response.setEntity(new GzipDecompressingEntity(response.getEntity())); return; } } } } }); return httpClient; }
From source file:ch.ethz.dcg.jukefox.commons.utils.AndroidUtils.java
public static DefaultHttpClient createHttpClientWithDefaultSettings() { HttpParams params = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(params, Constants.CONNECTION_TIMEOUT); HttpConnectionParams.setSoTimeout(params, Constants.CONNECTION_TIMEOUT); DefaultHttpClient httpClient = new DefaultHttpClient(params); HttpRequestRetryHandler retryHandler = new DefaultHttpRequestRetryHandler(2, true); httpClient.setHttpRequestRetryHandler(retryHandler); return httpClient; }
From source file:net.paissad.minus.utils.HttpClientUtils.java
/** * // w ww .j av a 2 s. c o m * @param baseURL * @param parametersBody * @param sessionId * @param fileToUpload - The file to upload. * @param filename - The name of the file to use during the upload process. * @return The response received from the Minus API. * @throws MinusException */ public static MinusHttpResponse doUpload(final String baseURL, final Map<String, String> parametersBody, final String sessionId, final File fileToUpload, final String filename) throws MinusException { DefaultHttpClient client = null; HttpPost uploadRequest = null; InputStream responseContent = null; try { String url = baseURL; if (parametersBody != null && !parametersBody.isEmpty()) { url += CommonUtils.encodeParams(parametersBody); } uploadRequest = new HttpPost(url); client = new DefaultHttpClient(); client.setHttpRequestRetryHandler(new MinusHttpRequestRetryHandler()); FileEntity fileEntity = new FileEntity(fileToUpload, "application/octet-stream"); uploadRequest.setEntity(fileEntity); // We add this headers as specified by the Minus.com API during file // upload. uploadRequest.addHeader("Content-Disposition", "attachment; filename=a.bin"); uploadRequest.addHeader("Content-Type", "application/octet-stream"); client.getParams().setParameter(ClientPNames.HANDLE_REDIRECTS, true); client.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BEST_MATCH); CookieStore cookieStore = new BasicCookieStore(); Cookie sessionCookie = null; if (sessionId != null && !sessionId.trim().isEmpty()) { sessionCookie = new BasicClientCookie2(MINUS_COOKIE_NAME, sessionId); ((BasicClientCookie2) sessionCookie).setPath("/"); ((BasicClientCookie2) sessionCookie).setDomain(MINUS_DOMAIN_NAME); ((BasicClientCookie2) sessionCookie).setVersion(0); cookieStore.addCookie(sessionCookie); } client.setCookieStore(cookieStore); HttpContext localContext = new BasicHttpContext(); localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore); HttpResponse httpResponse = client.execute(uploadRequest); // Let's update the cookie have the name 'sessionid' for (Cookie aCookie : client.getCookieStore().getCookies()) { if (aCookie.getName().equals(MINUS_COOKIE_NAME)) { sessionCookie = aCookie; break; } } StringBuilder result = new StringBuilder(); int statusCode = httpResponse.getStatusLine().getStatusCode(); if (statusCode == HttpStatus.SC_OK) { HttpEntity respEntity = httpResponse.getEntity(); if (respEntity != null) { result.append(EntityUtils.toString(respEntity)); EntityUtils.consume(respEntity); } } else { // The response code is not OK. StringBuilder errMsg = new StringBuilder(); errMsg.append(" Upload failed => ").append(httpResponse.getStatusLine()); if (uploadRequest != null) { errMsg.append(" : ").append(uploadRequest.getURI()); } throw new MinusException(errMsg.toString()); } return new MinusHttpResponse(result.toString(), sessionCookie); } catch (Exception e) { if (uploadRequest != null) { uploadRequest.abort(); } String errMsg = "Error while uploading file (" + fileToUpload + ") : " + e.getMessage(); throw new MinusException(errMsg, e); } finally { if (client != null) { client.getConnectionManager().shutdown(); } CommonUtils.closeAllStreamsQuietly(responseContent); } }
From source file:com.android.providers.downloads.OmaDownload.java
/** * This method notifies the server for the status of the download operation. * It sends a status report to a Web server if installNotify attribute is specified in the download descriptor. @param component the component that contains attributes in the descriptor. @param handler the handler used to send and process messages. A message indicates whether the media object is available to the user or not (READY or DISCARD). *//* w ww .j a v a2 s. c om*/ //protected static void installNotify (OmaDescription component, Handler handler) { protected static int installNotify(OmaDescription component, Handler handler) { int ack = -1; int release = OmaStatusHandler.DISCARD; URL url = component.getInstallNotifyUrl(); if (url != null) { DefaultHttpClient client = new DefaultHttpClient(); HttpPost postRequest = new HttpPost(url.toString()); try { HttpParams params = postRequest.getParams(); HttpProtocolParams.setUseExpectContinue(params, false); postRequest.setEntity( new StringEntity(OmaStatusHandler.statusCodeToString(component.getStatusCode()) + "\n\r")); } catch (UnsupportedEncodingException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } client.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler() { @Override public boolean retryRequest(IOException exception, int executionCount, HttpContext context) { // TODO Auto-generated method stub Log.i("@M_" + Constants.LOG_OMA_DL, "Retry the request..."); return (executionCount <= OmaStatusHandler.MAXIMUM_RETRY); } }); try { HttpResponse response = client.execute(postRequest); if (response.getStatusLine() != null) { ack = response.getStatusLine().getStatusCode(); //200-series response code if (ack == HttpStatus.SC_OK || ack == HttpStatus.SC_ACCEPTED || ack == HttpStatus.SC_CREATED || ack == HttpStatus.SC_MULTI_STATUS || ack == HttpStatus.SC_NON_AUTHORITATIVE_INFORMATION || ack == HttpStatus.SC_NO_CONTENT || ack == HttpStatus.SC_PARTIAL_CONTENT || ack == HttpStatus.SC_RESET_CONTENT) { if (component.getStatusCode() == OmaStatusHandler.SUCCESS) { release = OmaStatusHandler.READY; } } final HttpEntity entity = response.getEntity(); if (entity != null) { InputStream inputStream = null; try { inputStream = entity.getContent(); if (inputStream != null) { BufferedReader br = new BufferedReader(new InputStreamReader(inputStream)); String s; while ((s = br.readLine()) != null) { Log.v("@M_" + Constants.LOG_OMA_DL, "Response: " + s); } } } finally { if (inputStream != null) { inputStream.close(); } entity.consumeContent(); } } } } catch (ConnectTimeoutException e) { Log.e("@M_" + Constants.LOG_OMA_DL, e.toString()); postRequest.abort(); //After time out period, the client releases the media object for use. if (component.getStatusCode() == OmaStatusHandler.SUCCESS) { release = OmaStatusHandler.READY; } } catch (NoHttpResponseException e) { Log.e("@M_" + Constants.LOG_OMA_DL, e.toString()); postRequest.abort(); //After time out period, the client releases the media object for use. if (component.getStatusCode() == OmaStatusHandler.SUCCESS) { release = OmaStatusHandler.READY; } } catch (IOException e) { Log.e("@M_" + Constants.LOG_OMA_DL, e.toString()); postRequest.abort(); } if (client != null) { client.getConnectionManager().shutdown(); } } else { if (component.getStatusCode() == OmaStatusHandler.SUCCESS) { release = OmaStatusHandler.READY; } } if (handler != null) { Message mg = Message.obtain(); mg.arg1 = release; handler.sendMessage(mg); } return release; }
From source file:ph.sakay.gateway.APIClient.java
private HttpClient getHttpClient() { HttpParams httpParameters = new BasicHttpParams(); // Set the timeout in milliseconds until a connection is established. int timeoutConnection = 5000; HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection); // Set the default socket timeout (SO_TIMEOUT) // in milliseconds which is the timeout for waiting for data. int timeoutSocket = 300000; HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket); DefaultHttpClient client = new DefaultHttpClient(httpParameters); client.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler(1, false)); return client; }