List of usage examples for org.apache.http.params HttpConnectionParams setConnectionTimeout
public static void setConnectionTimeout(HttpParams httpParams, int i)
From source file:org.ttrssreader.net.deprecated.ApacheJSONConnector.java
protected InputStream doRequest(Map<String, String> params) { HttpPost post = new HttpPost(); try {/*ww w . ja va 2 s .c o m*/ if (sessionId != null) params.put(SID, sessionId); // Set Address post.setURI(Controller.getInstance().uri()); post.addHeader("Accept-Encoding", "gzip"); // Add POST data JSONObject json = new JSONObject(params); StringEntity jsonData = new StringEntity(json.toString(), "UTF-8"); jsonData.setContentType("application/json"); post.setEntity(jsonData); // Add timeouts for the connection { HttpParams httpParams = post.getParams(); // Set the timeout until a connection is established. int timeoutConnection = (int) (8 * Utils.SECOND); HttpConnectionParams.setConnectionTimeout(httpParams, timeoutConnection); // Set the default socket timeout (SO_TIMEOUT) which is the timeout for waiting for data. // use longer timeout when lazyServer-Feature is used int timeoutSocket = (int) ((Controller.getInstance().lazyServer()) ? 15 * Utils.MINUTE : 10 * Utils.SECOND); HttpConnectionParams.setSoTimeout(httpParams, timeoutSocket); post.setParams(httpParams); } logRequest(json); if (client == null) client = HttpClientFactory.getInstance().getHttpClient(post.getParams()); else client.setParams(post.getParams()); // Add SSL-Stuff if (credProvider != null) client.setCredentialsProvider(credProvider); } catch (URISyntaxException e) { hasLastError = true; lastError = "Invalid URI."; return null; } catch (Exception e) { hasLastError = true; lastError = "Error creating HTTP-Connection in (old) doRequest(): " + formatException(e); e.printStackTrace(); return null; } HttpResponse response; try { response = client.execute(post); // Execute the request } catch (ClientProtocolException e) { hasLastError = true; lastError = "ClientProtocolException in (old) doRequest(): " + formatException(e); return null; } catch (SSLPeerUnverifiedException e) { // Probably related: http://stackoverflow.com/questions/6035171/no-peer-cert-not-sure-which-route-to-take // Not doing anything here since this error should happen only when no certificate is received from the // server. Log.w(TAG, "SSLPeerUnverifiedException in (old) doRequest(): " + formatException(e)); return null; } catch (SSLException e) { if ("No peer certificate".equals(e.getMessage())) { // Handle this by ignoring it, this occurrs very often when the connection is instable. Log.w(TAG, "SSLException in (old) doRequest(): " + formatException(e)); } else { hasLastError = true; lastError = "SSLException in (old) doRequest(): " + formatException(e); } return null; } catch (InterruptedIOException e) { Log.w(TAG, "InterruptedIOException in (old) doRequest(): " + formatException(e)); return null; } catch (SocketException e) { // http://stackoverflow.com/questions/693997/how-to-set-httpresponse-timeout-for-android-in-java/1565243#1565243 Log.w(TAG, "SocketException in (old) doRequest(): " + formatException(e)); return null; } catch (Exception e) { hasLastError = true; lastError = "Exception in (old) doRequest(): " + formatException(e); return null; } // Try to check for HTTP Status codes int code = response.getStatusLine().getStatusCode(); if (code >= 400 && code < 600) { hasLastError = true; lastError = "Server returned status: " + code; return null; } InputStream instream = null; try { HttpEntity entity = response.getEntity(); if (entity != null) instream = entity.getContent(); // Try to decode gzipped instream, if it is not gzip we stay to normal reading Header contentEncoding = response.getFirstHeader("Content-Encoding"); if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) instream = new GZIPInputStream(instream); // Header size = response.getFirstHeader("Api-Content-Length"); // Log.d(TAG, "SIZE: " + size.getValue()); if (instream == null) { hasLastError = true; lastError = "Couldn't get InputStream in (old) Method doRequest(String url) [instream was null]"; return null; } } catch (Exception e) { if (instream != null) try { instream.close(); } catch (IOException e1) { // Empty! } hasLastError = true; lastError = "Exception in (old) doRequest(): " + formatException(e); return null; } return instream; }
From source file:com.dmsl.anyplace.googleapi.GMapV2Direction.java
public Document getDocument(double fromLatitude, double fromLongitude, GeoPoint toPosition, String mode) throws Exception { String url = "http://maps.googleapis.com/maps/api/directions/xml?" + "origin=" + fromLatitude + "," + fromLongitude + "&destination=" + toPosition.lat + "," + toPosition.lng + "&sensor=false&units=metric&mode=" + mode; HttpParams httpParameters = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpParameters, 20000); // 20seconds HttpConnectionParams.setSoTimeout(httpParameters, 20000); // 20 seconds HttpClient httpClient = new DefaultHttpClient(httpParameters); HttpPost httpPost = new HttpPost(url); HttpContext localContext = new BasicHttpContext(); HttpResponse response = httpClient.execute(httpPost, localContext); InputStream in = response.getEntity().getContent(); DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document doc = builder.parse(in); return doc;//from w w w .j a va 2 s . c om }
From source file:com.gs.tools.doc.extractor.core.util.HttpUtility.java
/** * Get data from HTTP POST method./*from ww w . j av a 2 s .co m*/ * * This method uses * <ul> * <li>Connection timeout = 300000 (5 minutes)</li> * <li>Socket/Read timeout = 300000 (5 minutes)</li> * <li>Socket Read Buffer = 10485760 (10MB) to provide more space to read</li> * </ul> * -- in case the site is slow * * @return * @throws MalformedURLException * @throws URISyntaxException * @throws UnsupportedEncodingException * @throws IOException * @throws ClientProtocolException * @throws Exception */ public static String getPostData(String sourceUrl, String postString) throws MalformedURLException, URISyntaxException, UnsupportedEncodingException, IOException, ClientProtocolException, Exception { String result = ""; URL targetUrl = new URL(sourceUrl); /* * Create http parameter to set Connection timeout = 300000 Socket/Read * timeout = 300000 Socket Read Buffer = 10485760 */ HttpParams httpParams = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpParams, 300000); HttpConnectionParams.setSocketBufferSize(httpParams, 10485760); HttpConnectionParams.setSoTimeout(httpParams, 300000); // set the http param to the DefaultHttpClient HttpClient httpClient = new DefaultHttpClient(httpParams); // create POST method and set the URL and POST data HttpPost post = new HttpPost(targetUrl.toURI()); StringEntity entity = new StringEntity(postString, "UTF-8"); post.setEntity(entity); logger.info("Execute the POST request with all input data"); // Execute the POST request on the http client to get the response HttpResponse response = httpClient.execute(post, new BasicHttpContext()); if (null != response && response.getStatusLine().getStatusCode() == 200) { HttpEntity httpEntity = response.getEntity(); if (null != httpEntity) { long contentLength = httpEntity.getContentLength(); logger.info("Content length: " + contentLength); // no data, if the content length is insufficient if (contentLength <= 0) { return ""; } // read the response to String InputStream responseStream = httpEntity.getContent(); if (null != responseStream) { BufferedReader reader = null; StringWriter writer = null; try { reader = new BufferedReader(new InputStreamReader(responseStream)); writer = new StringWriter(); int count = 0; int size = 1024 * 1024; char[] chBuff = new char[size]; while ((count = reader.read(chBuff, 0, size)) >= 0) { writer.write(chBuff, 0, count); } result = writer.getBuffer().toString(); } catch (Exception ex) { ex.printStackTrace(); throw ex; } finally { IOUtils.closeQuietly(responseStream); IOUtils.closeQuietly(reader); IOUtils.closeQuietly(writer); } } } } logger.info("data read complete"); return result; }
From source file:org.planetmono.dcuploader.Application.java
@Override public void onCreate() { HttpParams defaultParams = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(defaultParams, TIMEOUT_CONNECTION); HttpConnectionParams.setSoTimeout(defaultParams, TIMEOUT_SOCKET); client = new DefaultHttpClient(defaultParams); }
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 ww w .j ava 2 s . c o m }); 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.transdroid.search.BroadcasTheNet.BroadcasTheNetAdapter.java
private DefaultHttpClient prepareRequest(Context context) throws Exception { String username = SettingsHelper.getSiteUser(context, TorrentSite.BroadcasTheNet); String password = SettingsHelper.getSitePass(context, TorrentSite.BroadcasTheNet); if (username == null || password == null) { throw new InvalidParameterException( "No username or password was provided, while this is required for this private site."); }//from www . j ava2 s.co m // Setup request using GET HttpParams httpparams = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpparams, CONNECTION_TIMEOUT); HttpConnectionParams.setSoTimeout(httpparams, CONNECTION_TIMEOUT); DefaultHttpClient httpclient = new DefaultHttpClient(httpparams); // First log in HttpPost loginPost = new HttpPost(LOGINURL); loginPost.setEntity(new UrlEncodedFormEntity(Arrays.asList(new BasicNameValuePair[] { new BasicNameValuePair(LOGIN_USER, username), new BasicNameValuePair(LOGIN_PASS, password) }))); HttpResponse loginResult = httpclient.execute(loginPost); if (loginResult.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { // Failed to sign in throw new LoginException("Login failure for BroadcasTheNet with user " + username); } return httpclient; }
From source file:com.dss886.nForumSDK.NForumSDK.java
/** * ??appkey/*w w w .jav a 2s .c o m*/ * @param host ????http://api.byr.cn/ * HOST.HOST_* ? * @param username ?? * @param password ? */ public NForumSDK(String host, String username, String password) { httpClient = new DefaultHttpClient(); HttpParams param = httpClient.getParams(); HttpConnectionParams.setConnectionTimeout(param, timeout); HttpConnectionParams.setSoTimeout(param, timeout); httpClient = new DefaultHttpClient(param); auth = new String(Base64.encodeBase64((username + ":" + password).getBytes())); this.host = host; this.returnFormat = returnFormat + "?"; this.appkey = ""; }
From source file:com.jayqqaa12.abase.core.AHttp.java
public AHttp() { HttpParams params = new BasicHttpParams(); ConnManagerParams.setTimeout(params, AHttp.DEFAULT_CONN_TIMEOUT); HttpConnectionParams.setSoTimeout(params, AHttp.DEFAULT_CONN_TIMEOUT); HttpConnectionParams.setConnectionTimeout(params, AHttp.DEFAULT_CONN_TIMEOUT); ConnManagerParams.setMaxConnectionsPerRoute(params, new ConnPerRouteBean(10)); ConnManagerParams.setMaxTotalConnections(params, 10); HttpConnectionParams.setTcpNoDelay(params, true); HttpConnectionParams.setSocketBufferSize(params, 1024 * 8); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); schemeRegistry.register(new Scheme("https", DefaultSSLSocketFactory.getSocketFactory(), 443)); httpClient = new DefaultHttpClient(new ThreadSafeClientConnManager(params, schemeRegistry), params); httpClient.setHttpRequestRetryHandler(new RetryHandler(DEFAULT_RETRY_TIMES)); httpClient.addRequestInterceptor(new HttpRequestInterceptor() { @Override//from w w w. j a v a 2 s . co m public void process(org.apache.http.HttpRequest httpRequest, HttpContext httpContext) throws org.apache.http.HttpException, IOException { if (!httpRequest.containsHeader(HEADER_ACCEPT_ENCODING)) { httpRequest.addHeader(HEADER_ACCEPT_ENCODING, ENCODING_GZIP); } } }); httpClient.addResponseInterceptor(new HttpResponseInterceptor() { @Override public void process(HttpResponse response, HttpContext httpContext) throws org.apache.http.HttpException, IOException { 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("gzip")) { response.setEntity(new GZipDecompressingEntity(response.getEntity())); return; } } } } }); }
From source file:com.kubeiwu.commontool.khttp.toolbox.HttpClientStack.java
@Override public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders) throws IOException, AuthFailureError { HttpUriRequest httpRequest = createHttpRequest(request, additionalHeaders);// 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); }