List of usage examples for org.apache.http.params HttpConnectionParams setSoTimeout
public static void setSoTimeout(HttpParams httpParams, int i)
From source file:com.cndatacom.ordersystem.manager.AsyncHttpClient.java
/** * Creates a new AsyncHttpClient.//from w ww . jav a 2 s . co m */ public AsyncHttpClient() { BasicHttpParams httpParams = new BasicHttpParams(); ConnManagerParams.setTimeout(httpParams, socketTimeout); ConnManagerParams.setMaxConnectionsPerRoute(httpParams, new ConnPerRouteBean(maxConnections)); ConnManagerParams.setMaxTotalConnections(httpParams, DEFAULT_MAX_CONNECTIONS); HttpConnectionParams.setSoTimeout(httpParams, socketTimeout); HttpConnectionParams.setConnectionTimeout(httpParams, socketTimeout); HttpConnectionParams.setTcpNoDelay(httpParams, true); HttpConnectionParams.setSocketBufferSize(httpParams, DEFAULT_SOCKET_BUFFER_SIZE); HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1); HttpProtocolParams.setUserAgent(httpParams, String.format("android-async-http/%s (http://loopj.com/android-async-http)", VERSION)); SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443)); ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(httpParams, schemeRegistry); httpContext = new SyncBasicHttpContext(new BasicHttpContext()); httpClient = new DefaultHttpClient(cm, httpParams); httpClient.addRequestInterceptor(new HttpRequestInterceptor() { public void process(HttpRequest request, HttpContext context) { if (!request.containsHeader(HEADER_ACCEPT_ENCODING)) { request.addHeader(HEADER_ACCEPT_ENCODING, ENCODING_GZIP); } for (String header : clientHeaderMap.keySet()) { request.addHeader(header, clientHeaderMap.get(header)); } } }); httpClient.addResponseInterceptor(new HttpResponseInterceptor() { public void process(HttpResponse response, HttpContext context) { final HttpEntity entity = response.getEntity(); if (entity == null) { return; } final Header encoding = entity.getContentEncoding(); if (encoding != null) { for (HeaderElement element : encoding.getElements()) { if (element.getName().equalsIgnoreCase(ENCODING_GZIP)) { response.setEntity(new InflatingEntity(response.getEntity())); break; } } } } }); httpClient.setHttpRequestRetryHandler(new RetryHandler(DEFAULT_MAX_RETRIES)); threadPool = (ThreadPoolExecutor) Executors.newCachedThreadPool(); requestMap = new WeakHashMap<Context, List<WeakReference<Future<?>>>>(); clientHeaderMap = new HashMap<String, String>(); }
From source file:com.newtifry.android.remote.BackendClient.java
private HttpResponse requestNoRetryNoAccount(String urlPath, List<NameValuePair> params) throws Exception { // Make POST request DefaultHttpClient client = new DefaultHttpClient(); URI uri = new URI(BackendClient.defaultBackendName + urlPath); HttpPost post = new HttpPost(uri); final HttpParams getParams = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(getParams, 5000); HttpConnectionParams.setSoTimeout(getParams, 5000); UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, "UTF-8"); post.setEntity(entity);//from w w w . j av a2 s . c o m post.setHeader("X-Same-Domain", "1"); // XSRF HttpResponse res = client.execute(post); return res; }
From source file:de.fhg.iais.asc.oai.strategy.AbstractHarvester.java
/** * @param uri The repository url.//ww w . j a v a2s.c o m * @param metadataPrefix The metadata prefix to harvest. * @param proxyHost * @param proxyPort * @param fromDateParameter * @param untilDateParameter * @param config The current ASC configuration, non-<code>null</code>. * @param ascState the state object to report the progress, non-<code>null</code>. * @param ingestEvent The ingest event in which the harvesting takes place, non-<code>null</code>. */ public AbstractHarvester(String uri, String metadataPrefix, String proxyHost, Integer proxyPort, String fromDateParameter, String untilDateParameter, AscConfiguration config, ASCState ascState, AscProviderIngest ingestEvent) { Check.notNull(config, "config must be non-null"); Check.notNull(ascState, "ascState must be non-null"); Check.notNull(ingestEvent, "ingestEvent must be non-null"); this.uri = uri; this.metadataPrefix = metadataPrefix; this.fromDate = StringUtils.defaultIfEmpty(fromDateParameter, null); this.untilDate = StringUtils.defaultIfEmpty(untilDateParameter, null); int connectionTimeout = config.get(AscConfiguration.HARVESTING_CONNECTION_TIMEOUT, 600000); LOG.info("set connection and socket timeouts to approx. " + (connectionTimeout / 1000) + " seconds"); // request from a.schenk DDB-724 HttpParams httpParams = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpParams, connectionTimeout); HttpConnectionParams.setSoTimeout(httpParams, connectionTimeout); HttpClient client = new DefaultHttpClient(httpParams); // set some parameters that might help but will not harm // see: http://hc.apache.org/httpclient-legacy/preference-api.html // the user-agent: // tell them who we are (they see that from the IP anyway), thats a good habit, // shows that we are professional and not some script kiddies // and this is also a little bit of viral marketing :-) client.getParams().setParameter("http.useragent", "myCortex Harvester; http://www.iais.fraunhofer.de/"); // the following option "can result in noticeable performance improvement" (see api docs) // it may switch on a keep-alive, may reduce load on server side (if they are smart) // and might reduce latency client.getParams().setParameter("http.protocol.expect-continue", true); // ignore all cookies because some OAI-PMH implementations don't know how to handle cookies client.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.IGNORE_COOKIES); // setting of the proxy if needed if (proxyHost != null && !proxyHost.isEmpty()) { HttpHost proxy = new HttpHost(proxyHost, proxyPort); client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); } this.server = new OaiPmhServer(client, this.uri); this.config = config; this.ascState = ascState; this.ingestEvent = ingestEvent; }
From source file:edu.usf.cutr.opentripplanner.android.tasks.ServerChecker.java
@Override protected String doInBackground(Server... params) { Server server = params[0];/*from ww w. j av a 2 s. c om*/ if (server == null) { Log.w(TAG, "Tried to get server info when no server was selected"); cancel(true); } String message = context.getResources().getString(R.string.server_checker_info_dialog_region) + " " + server.getRegion(); message += "\n" + context.getResources().getString(R.string.server_checker_info_dialog_language) + " " + server.getLanguage(); message += "\n" + context.getResources().getString(R.string.server_checker_info_dialog_contact) + " " + server.getContactName() + " (" + server.getContactEmail() + ")"; message += "\n" + context.getResources().getString(R.string.server_checker_info_dialog_url) + " " + server.getBaseURL(); // TODO - fix server info bounds message += "\n" + context.getResources().getString(R.string.server_checker_info_dialog_bounds) + " " + server.getBounds(); message += "\n" + context.getResources().getString(R.string.server_checker_info_dialog_reachable) + " "; int status = 0; try { HttpParams httpParameters = new BasicHttpParams(); int timeoutConnection = context.getResources().getInteger(R.integer.connection_timeout); HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection); int timeoutSocket = context.getResources().getInteger(R.integer.socket_timeout); HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket); status = Http.get(server.getBaseURL() + "/plan").use(new DefaultHttpClient(httpParameters)).asResponse() .getStatusLine().getStatusCode(); } catch (IOException e) { Log.e(TAG, "Unable to reach server: " + e.getMessage()); message = context.getResources().getString(R.string.server_checker_error_message) + " " + e.getMessage(); return message; } if (status == HttpStatus.SC_OK) { message += context.getResources().getString(R.string.yes); isWorking = true; } else { message += context.getResources().getString(R.string.no); } return message; }
From source file:org.addhen.smssync.net.MainHttpClient.java
public MainHttpClient(String url, Context context) { this.url = url; this.context = context; this.params = new ArrayList<NameValuePair>(); this.headers = new HashMap<String, String>(); // default to GET this.method = "GET"; request = new HttpGet(url); httpParameters = new BasicHttpParams(); httpParameters.setParameter(ConnManagerPNames.MAX_TOTAL_CONNECTIONS, 1); httpParameters.setParameter(ConnManagerPNames.MAX_CONNECTIONS_PER_ROUTE, new ConnPerRouteBean(1)); httpParameters.setParameter(HttpProtocolParams.USE_EXPECT_CONTINUE, false); HttpProtocolParams.setVersion(httpParameters, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(httpParameters, "utf8"); // Set the timeout in milliseconds until a connection is established. HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection); // in milliseconds which is the timeout for waiting for data. HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket); SchemeRegistry schemeRegistry = new SchemeRegistry(); // http scheme schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); // https scheme try {// w w w . j av a 2s . c o m schemeRegistry.register(new Scheme("https", new TrustedSocketFactory(url, false), 443)); } catch (KeyManagementException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NoSuchAlgorithmException e) { // TODO Auto-generated catch block e.printStackTrace(); } ThreadSafeClientConnManager manager = new ThreadSafeClientConnManager(httpParameters, schemeRegistry); httpClient = new DefaultHttpClient(manager, httpParameters); // support basic auth header try { URI uri = new URI(url); String userInfo = uri.getUserInfo(); if (userInfo != null) { setHeader("Authorization", "Basic " + base64Encode(userInfo)); } } catch (URISyntaxException e) { debug(e); } // add user-agent header try { final String versionName = context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionName; // Add version name to user agent userAgent = new StringBuilder("SMSSync-Android/"); userAgent.append("v"); userAgent.append(versionName); setHeader("User-Agent", userAgent.toString()); } catch (NameNotFoundException e) { debug(e); } }
From source file:me.xiaopan.android.spear.download.HttpClientImageDownloader.java
public HttpClientImageDownloader() { this.urlLocks = Collections.synchronizedMap(new WeakHashMap<String, ReentrantLock>()); BasicHttpParams httpParams = new BasicHttpParams(); ConnManagerParams.setTimeout(httpParams, DEFAULT_WAIT_TIMEOUT); ConnManagerParams.setMaxConnectionsPerRoute(httpParams, new ConnPerRouteBean(DEFAULT_MAX_ROUTE_CONNECTIONS)); ConnManagerParams.setMaxTotalConnections(httpParams, DEFAULT_MAX_CONNECTIONS); HttpConnectionParams.setTcpNoDelay(httpParams, true); HttpConnectionParams.setSoTimeout(httpParams, DEFAULT_READ_TIMEOUT); HttpConnectionParams.setConnectionTimeout(httpParams, DEFAULT_CONNECT_TIMEOUT); HttpConnectionParams.setSocketBufferSize(httpParams, DEFAULT_SOCKET_BUFFER_SIZE); HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1); HttpProtocolParams.setUserAgent(httpParams, DEFAULT_USER_AGENT); SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443)); httpClient = new DefaultHttpClient(new ThreadSafeClientConnManager(httpParams, schemeRegistry), httpParams); httpClient.addRequestInterceptor(new GzipProcessRequestInterceptor()); httpClient.addResponseInterceptor(new GzipProcessResponseInterceptor()); }
From source file:de.escidoc.core.common.util.service.ConnectionUtility.java
private static void init() { /*//from ww w.ja v a 2 s. c o m * Configuration independant settings and default values. */ // ConnectionManager CONN_MANAGER.setMaxTotal(HTTP_MAX_TOTAL_CONNECTIONS_FACTOR); CONN_MANAGER.setDefaultMaxPerRoute(HTTP_MAX_CONNECTIONS_PER_HOST); // Default HttpParams HttpConnectionParams.setConnectionTimeout(DEFAULT_HTTP_PARAMS, DEFAULT_CONNECTION_TIMEOUT); HttpConnectionParams.setSoTimeout(DEFAULT_HTTP_PARAMS, DEFAULT_SO_TIMEOUT); /* * Configuration dependant settins. */ final EscidocConfiguration config = EscidocConfiguration.getInstance(); if (config == null) { if (LOG.isWarnEnabled()) { LOG.warn("Unable to get eSciDoc configuration."); } return; } // Proxy configuration: non proxy hosts (exclusions) String nonProxyHosts = config.get(EscidocConfiguration.ESCIDOC_CORE_NON_PROXY_HOSTS); if (nonProxyHosts != null && nonProxyHosts.trim().length() != 0) { nonProxyHosts = nonProxyHosts.replaceAll("\\.", "\\\\."); nonProxyHosts = nonProxyHosts.replaceAll("\\*", ""); nonProxyHosts = nonProxyHosts.replaceAll("\\?", "\\\\?"); NON_PROXY_HOSTS_PATTERN = Pattern.compile(nonProxyHosts); } // Proxy configuration: The proxy host to use final String proxyHostName = config.get(EscidocConfiguration.ESCIDOC_CORE_PROXY_HOST); final String proxyPort = config.get(EscidocConfiguration.ESCIDOC_CORE_PROXY_PORT); if (proxyHostName != null && !proxyHostName.isEmpty()) { PROXY_HOST = proxyPort != null && !proxyPort.isEmpty() ? new HttpHost(proxyHostName, Integer.parseInt(proxyPort)) : new HttpHost(proxyHostName); } // HttpClient configuration String property = null; if ((property = config.get(EscidocConfiguration.HTTP_CONNECTION_TIMEOUT)) != null) { try { HttpConnectionParams.setConnectionTimeout(DEFAULT_HTTP_PARAMS, Integer.parseInt(property)); } catch (final NumberFormatException e) { if (LOG.isWarnEnabled()) { LOG.warn("Unable to use the " + EscidocConfiguration.HTTP_CONNECTION_TIMEOUT + " property.", e); } } } if ((property = config.get(EscidocConfiguration.HTTP_SOCKET_TIMEOUT)) != null) { try { HttpConnectionParams.setSoTimeout(DEFAULT_HTTP_PARAMS, Integer.parseInt(property)); } catch (final NumberFormatException e) { if (LOG.isWarnEnabled()) { LOG.warn("Unable to use the " + EscidocConfiguration.HTTP_SOCKET_TIMEOUT + " property.", e); } } } }
From source file:org.openremote.controller.servlet.LoginServlet.java
/** * Check username and password against the online interface * @param username The OpenRemote Composer username * @param password The OpenRemote Composer password * @return 0 if valid, -1 if not yet synced, -2 if invalid, -3 if different user *///from w ww. j a v a2 s . co m public int checkOnline(String username, String password) { String databaseuser = configurationService.getItem("composer_username"); String databasepassword = configurationService.getItem("composer_password"); if (!databaseuser.equals("") && !username.equals(databaseuser)) { return -3; } HttpParams params = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(params, timeout); HttpConnectionParams.setSoTimeout(params, timeout); HttpClient httpClient = new DefaultHttpClient(params); HttpGet httpGet = new HttpGet(PathUtil.addSlashSuffix(configuration.getBeehiveRESTRootUrl()) + "user/" + username + "/openremote.zip"); httpGet.setHeader(Constants.HTTP_AUTHORIZATION_HEADER, Constants.HTTP_BASIC_AUTHORIZATION + encode(username, password)); boolean success = false; try { HttpResponse resp = httpClient.execute(httpGet); int statuscode = resp.getStatusLine().getStatusCode(); if (200 == statuscode) { if (!configurationService.getBooleanItem(FIRST_TIME_SYNC)) { if (databaseuser == null || databaseuser.equals("")) { success = fileService.writeZipAndUnzip(resp.getEntity().getContent()); if (success) { controllerXMLChangeService.refreshController(); } } } if (!configurationService.getItem("composer_password").equals(this.getHashedPassword(password))) { this.generateSalt(); saveCredentials(username, password); } return 0; } else if (401 == statuscode) { return -2; } else { logger.error("Login checking failed with HTTP Code " + statuscode); } } catch (IOException e) { logger.error(e.getMessage()); } if (databaseuser.equals("") && databasepassword.equals("")) { saveCredentials(username, password); return 0; } else if (username.equals(username) && this.getHashedPassword(password).equals(databasepassword)) { return 0; } else { return -2; } }
From source file:com.vaushell.treetasker.client.SimpleJsonClient.java
private void init() { resource = null;//from ww w .ja v a 2s . c o m path = null; HttpParams httpParameters = client.getParams(); HttpConnectionParams.setConnectionTimeout(httpParameters, TIMEOUT_CONNECTION); HttpConnectionParams.setSoTimeout(httpParameters, TIMEOUT_SOCKET); client.setParams(httpParameters); }