Java Code Examples for org.apache.http.params.HttpConnectionParams#setConnectionTimeout()
The following examples show how to use
org.apache.http.params.HttpConnectionParams#setConnectionTimeout() .
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: HttpClientFactory.java From miappstore with Apache License 2.0 | 6 votes |
private static HttpParams createHttpParams() { final HttpParams params = new BasicHttpParams(); // 设置是否启用旧连接检查,默认是开启的。关闭这个旧连接检查可以提高一点点性能,但是增加了I/O错误的风险(当服务端关闭连接时)。 // 开启这个选项则在每次使用老的连接之前都会检查连接是否可用,这个耗时大概在15-30ms之间 HttpConnectionParams.setStaleCheckingEnabled(params, false); HttpConnectionParams.setConnectionTimeout(params, TIMEOUT);// 设置链接超时时间 HttpConnectionParams.setSoTimeout(params, TIMEOUT);// 设置socket超时时间 HttpConnectionParams.setSocketBufferSize(params, SOCKET_BUFFER_SIZE);// 设置缓存大小 HttpConnectionParams.setTcpNoDelay(params, true);// 是否不使用延迟发送(true为不延迟) HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); // 设置协议版本 HttpProtocolParams.setUseExpectContinue(params, true);// 设置异常处理机制 HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);// 设置编码 HttpClientParams.setRedirecting(params, false);// 设置是否采用重定向 ConnManagerParams.setTimeout(params, TIMEOUT);// 设置超时 ConnManagerParams.setMaxConnectionsPerRoute(params, new ConnPerRouteBean(MAX_CONNECTIONS));// 多线程最大连接数 ConnManagerParams.setMaxTotalConnections(params, 10); // 多线程总连接数 return params; }
Example 2
Source File: HttpClientStack.java From WayHoo with Apache License 2.0 | 5 votes |
@Override public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders) throws IOException, AuthFailureError { HttpUriRequest httpRequest = createHttpRequest(request, additionalHeaders); addHeaders(httpRequest, additionalHeaders); addHeaders(httpRequest, request.getHeaders()); onPrepareRequest(httpRequest); HttpParams httpParams = httpRequest.getParams(); int timeoutMs = request.getTimeoutMs(); // TODO: Reevaluate this connection timeout based on more wide-scale // data collection and possibly different for wifi vs. 3G. HttpConnectionParams.setConnectionTimeout(httpParams, 5000); HttpConnectionParams.setSoTimeout(httpParams, timeoutMs); return mClient.execute(httpRequest); }
Example 3
Source File: AsyncHttpClient.java From Libraries-for-Android-Developers with MIT License | 5 votes |
/** * Set the connection and socket timeout. By default, 10 seconds. * * @param timeout the connect/socket timeout in milliseconds, at least 1 second */ public void setTimeout(int timeout) { if (timeout < 1000) timeout = DEFAULT_SOCKET_TIMEOUT; this.timeout = timeout; final HttpParams httpParams = this.httpClient.getParams(); ConnManagerParams.setTimeout(httpParams, this.timeout); HttpConnectionParams.setSoTimeout(httpParams, this.timeout); HttpConnectionParams.setConnectionTimeout(httpParams, this.timeout); }
Example 4
Source File: HttpClientStack.java From android_tv_metro with Apache License 2.0 | 5 votes |
@Override public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders) throws IOException, AuthFailureError { HttpUriRequest httpRequest = createHttpRequest(request, additionalHeaders); addHeaders(httpRequest, additionalHeaders); addHeaders(httpRequest, request.getHeaders()); onPrepareRequest(httpRequest); HttpParams httpParams = httpRequest.getParams(); int timeoutMs = request.getTimeoutMs(); // TODO: Reevaluate this connection timeout based on more wide-scale // data collection and possibly different for wifi vs. 3G. HttpConnectionParams.setConnectionTimeout(httpParams, 5000); HttpConnectionParams.setSoTimeout(httpParams, timeoutMs); return mClient.execute(httpRequest); }
Example 5
Source File: HttpUtils.java From BigApp_Discuz_Android with Apache License 2.0 | 5 votes |
public HttpUtils configTimeout(int timeout) { final HttpParams httpParams = this.httpClient.getParams(); ConnManagerParams.setTimeout(httpParams, timeout); HttpConnectionParams.setSoTimeout(httpParams, timeout); HttpConnectionParams.setConnectionTimeout(httpParams, timeout); return this; }
Example 6
Source File: RestService.java From kylin-on-parquet-v2 with Apache License 2.0 | 5 votes |
private HttpClient getHttpClient(int connectionTimeout, int readTimeout) { final HttpParams httpParams = new BasicHttpParams(); HttpConnectionParams.setSoTimeout(httpParams, readTimeout); HttpConnectionParams.setConnectionTimeout(httpParams, connectionTimeout); return new DefaultHttpClient(httpParams); }
Example 7
Source File: HttpUtil.java From wakao-app with MIT License | 5 votes |
public static HttpClient getHttpClient() { HttpParams params = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(params, TIMEOUT_CONNECTION); HttpConnectionParams.setSoTimeout(params, TIMEOUT_SOCKET); HttpClient httpClient = new DefaultHttpClient(params); return httpClient; }
Example 8
Source File: RESTClient.java From product-ei with Apache License 2.0 | 5 votes |
/** * Constructor for RESTClient * * @param connectionTimeout connection time out in milliseconds * @param socketTimeout socket time out in milliseconds */ public RESTClient(int connectionTimeout, int socketTimeout) { setup(); HttpParams params = httpclient.getParams(); HttpConnectionParams.setConnectionTimeout(params, connectionTimeout); HttpConnectionParams.setSoTimeout(params, socketTimeout); }
Example 9
Source File: JenkinsHttpClient.java From verigreen with Apache License 2.0 | 5 votes |
/** * Create an unauthenticated Jenkins HTTP client * * @param uri * Location of the jenkins server (ex. http://localhost:8080) */ public JenkinsHttpClient(URI uri) { this.context = uri.getPath(); if (!context.endsWith("/")) { context += "/"; } this.uri = uri; this.mapper = getDefaultMapper(); HttpParams httpParameters = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpParameters, 10000); HttpConnectionParams.setSoTimeout(httpParameters, 10000); this.client = new DefaultHttpClient(new PoolingClientConnectionManager(), httpParameters); }
Example 10
Source File: HttpClientStack.java From volley_demo with Apache License 2.0 | 5 votes |
@Override public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders) throws IOException, AuthFailureError { HttpUriRequest httpRequest = createHttpRequest(request, additionalHeaders); addHeaders(httpRequest, additionalHeaders); addHeaders(httpRequest, request.getHeaders()); onPrepareRequest(httpRequest); HttpParams httpParams = httpRequest.getParams(); int timeoutMs = request.getTimeoutMs(); // TODO: Reevaluate this connection timeout based on more wide-scale // data collection and possibly different for wifi vs. 3G. HttpConnectionParams.setConnectionTimeout(httpParams, 5000); HttpConnectionParams.setSoTimeout(httpParams, timeoutMs); return mClient.execute(httpRequest); }
Example 11
Source File: OneKeyWifi.java From zhangshangwuda with Apache License 2.0 | 5 votes |
public static HttpClient getNewHttpClient() { try { KeyStore trustStore = KeyStore.getInstance(KeyStore .getDefaultType()); trustStore.load(null, null); SSLSocketFactory sf = new SSLSocketFactoryEx(trustStore); sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); HttpParams params = new BasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, HTTP.UTF_8); HttpConnectionParams.setConnectionTimeout(params, 5 * 1000); HttpConnectionParams.setSoTimeout(params, 5 * 1000); SchemeRegistry registry = new SchemeRegistry(); registry.register(new Scheme("http", PlainSocketFactory .getSocketFactory(), 80)); registry.register(new Scheme("https", sf, 443)); ClientConnectionManager ccm = new ThreadSafeClientConnManager( params, registry); return new DefaultHttpClient(ccm, params); } catch (Exception e) { return new DefaultHttpClient(); } }
Example 12
Source File: SettingsService.java From subsonic with GNU General Public License v3.0 | 5 votes |
private void validateLicense() { String email = getLicenseEmail(); Date date = getLicenseDate(); if (email == null || date == null) { licenseValidated = false; return; } HttpClient client = new DefaultHttpClient(); HttpConnectionParams.setConnectionTimeout(client.getParams(), 120000); HttpConnectionParams.setSoTimeout(client.getParams(), 120000); HttpGet method = new HttpGet("http://subsonic.org/backend/validateLicense.view" + "?email=" + StringUtil.urlEncode(email) + "&date=" + date.getTime() + "&version=" + versionService.getLocalVersion()); try { ResponseHandler<String> responseHandler = new BasicResponseHandler(); String content = client.execute(method, responseHandler); licenseValidated = content != null && !content.contains("false"); if (!licenseValidated) { LOG.warn("License key is not valid."); } String[] lines = StringUtils.split(content); if (lines.length > 1) { licenseExpires = new Date(Long.parseLong(lines[1])); } } catch (Throwable x) { LOG.warn("Failed to validate license.", x); } finally { client.getConnectionManager().shutdown(); } }
Example 13
Source File: StreamClientImpl.java From openhab1-addons with Eclipse Public License 2.0 | 4 votes |
public StreamClientImpl(StreamClientConfigurationImpl configuration) throws InitializationException { this.configuration = configuration; ConnManagerParams.setMaxTotalConnections(globalParams, getConfiguration().getMaxTotalConnections()); HttpConnectionParams.setConnectionTimeout(globalParams, getConfiguration().getConnectionTimeoutSeconds() * 1000); HttpConnectionParams.setSoTimeout(globalParams, getConfiguration().getDataReadTimeoutSeconds() * 1000); HttpProtocolParams.setContentCharset(globalParams, getConfiguration().getContentCharset()); if (getConfiguration().getSocketBufferSize() != -1) { // Android configuration will set this to 8192 as its httpclient is based // on a random pre 4.0.1 snapshot whose BasicHttpParams do not set a default value for socket buffer size. // This will also avoid OOM on the HTC Thunderbolt where default size is 2Mb (!): // http://stackoverflow.com/questions/5358014/android-httpclient-oom-on-4g-lte-htc-thunderbolt HttpConnectionParams.setSocketBufferSize(globalParams, getConfiguration().getSocketBufferSize()); } HttpConnectionParams.setStaleCheckingEnabled(globalParams, getConfiguration().getStaleCheckingEnabled()); // This is a pretty stupid API... https://issues.apache.org/jira/browse/HTTPCLIENT-805 SchemeRegistry registry = new SchemeRegistry(); registry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory())); // The 80 here is... useless clientConnectionManager = new ThreadSafeClientConnManager(globalParams, registry); httpClient = new DefaultHttpClient(clientConnectionManager, globalParams); if (getConfiguration().getRequestRetryCount() != -1) { httpClient.setHttpRequestRetryHandler( new DefaultHttpRequestRetryHandler(getConfiguration().getRequestRetryCount(), false)); } /* * // TODO: Ugh! And it turns out that by default it doesn't even use persistent connections properly! * * @Override * protected ConnectionReuseStrategy createConnectionReuseStrategy() { * return new NoConnectionReuseStrategy(); * } * * @Override * protected ConnectionKeepAliveStrategy createConnectionKeepAliveStrategy() { * return new ConnectionKeepAliveStrategy() { * public long getKeepAliveDuration(HttpResponse httpResponse, HttpContext httpContext) { * return 0; * } * }; * } * httpClient.removeRequestInterceptorByClass(RequestConnControl.class); */ }
Example 14
Source File: PodcastService.java From subsonic with GNU General Public License v3.0 | 4 votes |
@SuppressWarnings({"unchecked"}) private void doRefreshChannel(PodcastChannel channel, boolean downloadEpisodes) { InputStream in = null; HttpClient client = new DefaultHttpClient(); try { channel.setStatus(PodcastStatus.DOWNLOADING); channel.setErrorMessage(null); podcastDao.updateChannel(channel); HttpConnectionParams.setConnectionTimeout(client.getParams(), 2 * 60 * 1000); // 2 minutes HttpConnectionParams.setSoTimeout(client.getParams(), 10 * 60 * 1000); // 10 minutes HttpGet method = new HttpGet(channel.getUrl()); HttpResponse response = client.execute(method); in = response.getEntity().getContent(); Document document = new SAXBuilder().build(in); Element channelElement = document.getRootElement().getChild("channel"); channel.setTitle(StringUtil.removeMarkup(channelElement.getChildTextTrim("title"))); channel.setDescription(StringUtil.removeMarkup(channelElement.getChildTextTrim("description"))); channel.setImageUrl(getChannelImageUrl(channelElement)); channel.setStatus(PodcastStatus.COMPLETED); channel.setErrorMessage(null); podcastDao.updateChannel(channel); downloadImage(channel); refreshEpisodes(channel, channelElement.getChildren("item")); } catch (Exception x) { LOG.warn("Failed to get/parse RSS file for Podcast channel " + channel.getUrl(), x); channel.setStatus(PodcastStatus.ERROR); channel.setErrorMessage(getErrorMessage(x)); podcastDao.updateChannel(channel); } finally { IOUtils.closeQuietly(in); client.getConnectionManager().shutdown(); } if (downloadEpisodes) { for (final PodcastEpisode episode : getEpisodes(channel.getId())) { if (episode.getStatus() == PodcastStatus.NEW && episode.getUrl() != null) { downloadEpisode(episode); } } } }
Example 15
Source File: HTTPService.java From FanXin-based-HuanXin with GNU General Public License v2.0 | 4 votes |
/** * Get 请求 * * @param url */ public String[] getRequest(String url, String cookie) { HttpParams httpparams = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpparams, CONNECTION_TIMEOUT); HttpClient client = new DefaultHttpClient(httpparams); HttpGet get = new HttpGet(url); if (cookie != null) { get.addHeader("Cookie", cookie); } try { HttpResponse response = client.execute(get); int statusCode = response.getStatusLine().getStatusCode(); HttpEntity entity = response.getEntity(); String result = EntityUtils.toString(entity, "utf-8"); String message = ""; if (statusCode == 200) { message = "ok"; } else if (statusCode == 500) { message = "服务器内部错误"; } else { if (result != null) { JSONObject obj = JSON.parseObject(result); if (obj != null && obj.containsKey("error")) { message = obj.getString("error"); } else { message = "发生未知错误"; } } else { message = "发生未知错误"; } } return new String[] { statusCode + "", result, message }; } catch (Exception e) { Log.i(TAG, e.getMessage()); } return null; }
Example 16
Source File: HttpClientConnectionFactory.java From dubbox with Apache License 2.0 | 4 votes |
public void setHessianProxyFactory(HessianProxyFactory factory) { HttpConnectionParams.setConnectionTimeout(httpClient.getParams(), (int) factory.getConnectTimeout()); HttpConnectionParams.setSoTimeout(httpClient.getParams(), (int) factory.getReadTimeout()); }
Example 17
Source File: VersionService.java From subsonic with GNU General Public License v3.0 | 4 votes |
/** * Resolves the latest available Subsonic version by screen-scraping a web page. * * @throws IOException If an I/O error occurs. */ private void readLatestVersion() throws IOException { HttpClient client = new DefaultHttpClient(); HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000); HttpConnectionParams.setSoTimeout(client.getParams(), 10000); HttpGet method = new HttpGet(VERSION_URL + "?v=" + getLocalVersion()); String content; try { ResponseHandler<String> responseHandler = new BasicResponseHandler(); content = client.execute(method, responseHandler); } finally { client.getConnectionManager().shutdown(); } BufferedReader reader = new BufferedReader(new StringReader(content)); Pattern finalPattern = Pattern.compile("SUBSONIC_FULL_VERSION_BEGIN(.*)SUBSONIC_FULL_VERSION_END"); Pattern betaPattern = Pattern.compile("SUBSONIC_BETA_VERSION_BEGIN(.*)SUBSONIC_BETA_VERSION_END"); try { String line = reader.readLine(); while (line != null) { Matcher finalMatcher = finalPattern.matcher(line); if (finalMatcher.find()) { latestFinalVersion = new Version(finalMatcher.group(1)); LOG.info("Resolved latest Subsonic final version to: " + latestFinalVersion); } Matcher betaMatcher = betaPattern.matcher(line); if (betaMatcher.find()) { latestBetaVersion = new Version(betaMatcher.group(1)); LOG.info("Resolved latest Subsonic beta version to: " + latestBetaVersion); } line = reader.readLine(); } } finally { reader.close(); } }
Example 18
Source File: RuntimeHttpUtils.java From ibm-cos-sdk-java with Apache License 2.0 | 4 votes |
/** * Fetches a file from the URI given and returns an input stream to it. * * @param uri the uri of the file to fetch * @param config optional configuration overrides * @return an InputStream containing the retrieved data * @throws IOException on error */ @SuppressWarnings("deprecation") public static InputStream fetchFile( final URI uri, final ClientConfiguration config) throws IOException { HttpParams httpClientParams = new BasicHttpParams(); HttpProtocolParams.setUserAgent( httpClientParams, getUserAgent(config, null)); HttpConnectionParams.setConnectionTimeout( httpClientParams, getConnectionTimeout(config)); HttpConnectionParams.setSoTimeout( httpClientParams, getSocketTimeout(config)); DefaultHttpClient httpclient = new DefaultHttpClient(httpClientParams); if (config != null) { String proxyHost = config.getProxyHost(); int proxyPort = config.getProxyPort(); if (proxyHost != null && proxyPort > 0) { HttpHost proxy = new HttpHost(proxyHost, proxyPort); httpclient.getParams().setParameter( ConnRoutePNames.DEFAULT_PROXY, proxy); if (config.getProxyUsername() != null && config.getProxyPassword() != null) { httpclient.getCredentialsProvider().setCredentials( new AuthScope(proxyHost, proxyPort), new NTCredentials(config.getProxyUsername(), config.getProxyPassword(), config.getProxyWorkstation(), config.getProxyDomain())); } } } HttpResponse response = httpclient.execute(new HttpGet(uri)); if (response.getStatusLine().getStatusCode() != 200) { throw new IOException("Error fetching file from " + uri + ": " + response); } return new HttpClientWrappingInputStream( httpclient, response.getEntity().getContent()); }
Example 19
Source File: TEvernoteHttpClient.java From EverMemo with MIT License | 4 votes |
public void setConnectTimeout(int timeout) { HttpConnectionParams.setConnectionTimeout(httpParameters, timeout); }
Example 20
Source File: HttpClientConnectionFactory.java From dubbox with Apache License 2.0 | 4 votes |
public void setHessianProxyFactory(HessianProxyFactory factory) { HttpConnectionParams.setConnectionTimeout(httpClient.getParams(), (int) factory.getConnectTimeout()); HttpConnectionParams.setSoTimeout(httpClient.getParams(), (int) factory.getReadTimeout()); }