List of usage examples for org.apache.http.params HttpConnectionParams setSoTimeout
public static void setSoTimeout(HttpParams httpParams, int i)
From source file:com.netflix.raigad.utils.SystemUtils.java
public static String runHttpPutCommand(String url, String jsonBody) throws IOException { String return_; DefaultHttpClient client = new DefaultHttpClient(); InputStream isStream = null;//from www.java2s .c om try { HttpParams httpParameters = new BasicHttpParams(); int timeoutConnection = 1000; int timeoutSocket = 1000; HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection); HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket); client.setParams(httpParameters); HttpPut putRequest = new HttpPut(url); putRequest.setEntity(new StringEntity(jsonBody, StandardCharsets.UTF_8)); putRequest.setHeader("Content-type", "application/json"); HttpResponse resp = client.execute(putRequest); if (resp == null || resp.getEntity() == null) { throw new ESHttpException("Unable to execute PUT URL (" + url + ") Exception Message: < Null Response or Null HttpEntity >"); } isStream = resp.getEntity().getContent(); if (resp.getStatusLine().getStatusCode() != 200) { throw new ESHttpException("Unable to execute PUT URL (" + url + ") Exception Message: (" + IOUtils.toString(isStream, StandardCharsets.UTF_8.toString()) + ")"); } return_ = IOUtils.toString(isStream, StandardCharsets.UTF_8.toString()); logger.debug("PUT URL API: {} with JSONBody {} returns: {}", url, jsonBody, return_); } catch (Exception e) { throw new ESHttpException( "Caught an exception during execution of URL (" + url + ")Exception Message: (" + e + ")"); } finally { if (isStream != null) isStream.close(); } return return_; }
From source file:com.networkmanagerapp.JSONBackgroundDownloaderService.java
/** * Delegate method to run the specified intent in another thread. * @param arg0 The intent to run in the background *//*from w ww.j a va 2s.c o m*/ @Override protected void onHandleIntent(Intent arg0) { mNM = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); showNotification(); String filename = arg0.getStringExtra("FILENAME"); String jsonFile = arg0.getStringExtra("JSONFILE"); try { String password = PreferenceManager.getDefaultSharedPreferences(this).getString("password_preference", ""); Log.d("password", password); String ip = PreferenceManager.getDefaultSharedPreferences(this).getString("ip_preference", "192.168.1.1"); String enc = URLEncoder.encode(ip, "UTF-8"); String scriptUrl = "http://" + enc + ":1080" + filename; HttpParams params = new BasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, "utf-8"); // Set the timeout in milliseconds until a connection is established. int timeoutConnection = 3000; HttpConnectionParams.setConnectionTimeout(params, timeoutConnection); // Set the default socket timeout (SO_TIMEOUT) // in milliseconds which is the timeout for waiting for data. int timeoutSocket = 20000; HttpConnectionParams.setSoTimeout(params, timeoutSocket); HttpHost targetHost = new HttpHost(enc, 1080, "http"); DefaultHttpClient client = new DefaultHttpClient(params); client.getCredentialsProvider().setCredentials( new AuthScope(targetHost.getHostName(), targetHost.getPort()), new UsernamePasswordCredentials("root", password)); HttpGet request = new HttpGet(scriptUrl); HttpResponse response = client.execute(targetHost, request); Log.d("JBDS", response.getStatusLine().toString()); InputStream in = response.getEntity().getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); StringBuilder str = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { str.append(line + "\n"); } in.close(); if (str.toString().equals("Success\n")) { String xmlUrl = "http://" + enc + ":1080/json" + jsonFile; request = new HttpGet(xmlUrl); HttpResponse jsonData = client.execute(targetHost, request); in = jsonData.getEntity().getContent(); reader = new BufferedReader(new InputStreamReader(in)); str = new StringBuilder(); line = null; while ((line = reader.readLine()) != null) { str.append(line + "\n"); } in.close(); FileOutputStream fos = openFileOutput(jsonFile.substring(1), Context.MODE_PRIVATE); fos.write(str.toString().getBytes()); fos.close(); } } catch (MalformedURLException ex) { Log.e("NETWORKMANAGER_XBD_MUE", ex.getMessage()); } catch (IOException e) { try { Log.e("NETWORK_MANAGER_XBD_IOE", e.getMessage()); StackTraceElement[] st = e.getStackTrace(); for (int i = 0; i < st.length; i++) { Log.e("NETWORK_MANAGER_XBD_IOE", st[i].toString()); } } catch (NullPointerException ex) { Log.e("Network_manager_xbd_npe", ex.getLocalizedMessage()); } } finally { mNM.cancel(R.string.download_service_started); Intent bci = new Intent(NEW_DATA_AVAILABLE); sendBroadcast(bci); stopSelf(); } }
From source file:org.fashiontec.bodyapps.sync.Sync.java
/** * Manages put requests// w w w.j a v a 2 s . c o m * * @param url * @param json * @param conTimeOut * @param socTimeOut * @return */ public HttpResponse put(String url, String json, int conTimeOut, int socTimeOut) { HttpResponse response = null; try { HttpParams httpParameters = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpParameters, conTimeOut); HttpConnectionParams.setSoTimeout(httpParameters, socTimeOut); HttpClient client = new DefaultHttpClient(httpParameters); HttpPut request = new HttpPut(url); StringEntity se = new StringEntity(json); request.setEntity(se); request.setHeader("Accept", "application/json"); request.setHeader("Content-type", "application/json"); response = client.execute(request); } catch (Exception e) { Log.e(TAG, e.getMessage()); } return response; }
From source file:fr.gcastel.freeboxV6GeekIncDownloader.services.FreeboxDownloaderService.java
private String loginFreebox(String password) throws UnsupportedEncodingException, ClientProtocolException, IOException { String cookieFbx = ""; String csrfToken = ""; // Prparation des paramtres HttpPost postReq = new HttpPost(urlFreebox + "/login.php"); List<NameValuePair> parametres = new ArrayList<NameValuePair>(); parametres.add(new BasicNameValuePair("login", "freebox")); parametres.add(new BasicNameValuePair("passwd", password)); postReq.setEntity(new UrlEncodedFormEntity(parametres)); // Envoi de la requte HttpParams httpParameters = new BasicHttpParams(); // Mise en place de timeouts int timeoutConnection = 5000; HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection); int timeoutSocket = 5000; HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket); HttpClient httpclient = new DefaultHttpClient(httpParameters); HttpParams params = httpclient.getParams(); HttpClientParams.setRedirecting(params, false); HttpResponse response = httpclient.execute(postReq); // Ok ? (302 = moved = redirection) if (response.getStatusLine().getStatusCode() == 302) { Header cookie = response.getFirstHeader("Set-Cookie"); cookieFbx = cookie.getValue();/*www .j a v a 2 s. c o m*/ // Extraction du cookie FBXSID cookieFbx = cookieFbx.substring(cookieFbx.indexOf("FBXSID=\""), cookieFbx.indexOf("\";") + 1); Log.d(TAG, "Cookie = " + cookieFbx); } else { Log.d(TAG, "Erreur d'authentification - statusCode = " + response.getStatusLine().getStatusCode() + " - reason = " + response.getStatusLine().getReasonPhrase()); prepareAlertDialog("Erreur d'authentification"); } // On a le cookie, il nous manque le csrf_token // On rcupre la page download ! HttpGet downloadPageReq = new HttpGet(urlFreebox + "/download.php"); downloadPageReq.setHeader("Cookie", "FBXSID=\"" + cookieFbx + "\";"); response = httpclient.execute(downloadPageReq); // Ok ? if (response.getStatusLine().getStatusCode() == 200) { HttpEntity entity = response.getEntity(); InputStream contentStream = entity.getContent(); BufferedReader br = new BufferedReader(new InputStreamReader(contentStream)); String line = br.readLine(); while (line != null) { if (line.contains("input type=\"hidden\" name=\"csrf_token\"")) { csrfToken = line.substring(line.indexOf("value=\"") + "value=\"".length(), line.lastIndexOf("\"")); break; } line = br.readLine(); } br.close(); contentStream.close(); Log.d(TAG, "csrfToken = " + csrfToken); } else { Log.d(TAG, "Erreur d'authentification - statusCode = " + response.getStatusLine().getStatusCode() + " - reason = " + response.getStatusLine().getReasonPhrase()); prepareAlertDialog("Erreur d'authentification"); } // C'est moche, mais a me permet de corriger a vite fait... return cookieFbx + "<-->" + csrfToken; }
From source file:com.bbxiaoqu.api.AndroidHttpClient.java
/** * Create a new HttpClient with reasonable defaults (which you can update). * * @param userAgent to report in your HTTP requests * @param context to use for caching SSL sessions (may be null for no caching) * @return AndroidHttpClient for you to use for all your requests. *//*www.j a va 2s . c om*/ public static AndroidHttpClient newInstance(String userAgent, Context context) { HttpParams params = new BasicHttpParams(); // Turn off stale checking. Our connections break all the time anyway, // and it's not worth it to pay the penalty of checking every time. HttpConnectionParams.setStaleCheckingEnabled(params, false); // Default connection and socket timeout of 20 seconds. Tweak to taste. HttpConnectionParams.setConnectionTimeout(params, 20000); HttpConnectionParams.setSoTimeout(params, 20000); HttpConnectionParams.setSocketBufferSize(params, 8192); // Increase max total connection to 60 ConnManagerParams.setMaxTotalConnections(params, 60); // Increase default max connection per route to 20 ConnPerRouteBean connPerRoute = new ConnPerRouteBean(20); // Increase max connections for localhost:80 to 20 HttpHost localhost = new HttpHost("locahost", 80); connPerRoute.setMaxForRoute(new HttpRoute(localhost), 20); ConnManagerParams.setMaxConnectionsPerRoute(params, connPerRoute); // Don't handle redirects -- return them to the caller. Our code // often wants to re-POST after a redirect, which we must do ourselves. HttpClientParams.setRedirecting(params, false); // Use a session cache for SSL sockets // SSLSessionCache sessionCache = context == null ? null : new SSLSessionCache(context); // SSLCertificateSocketFactory.getDefault (30 * 1000); // Set the specified user agent and register standard protocols. HttpProtocolParams.setUserAgent(params, userAgent); SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443)); ClientConnectionManager manager = new ThreadSafeClientConnManager(params, schemeRegistry); // We use a factory method to modify superclass initialization // parameters without the funny call-a-static-method dance. return new AndroidHttpClient(manager, params); }
From source file:org.transdroid.daemon.util.HttpHelper.java
/** * Creates a standard Apache HttpClient that is thread safe, supports different SSL auth methods and basic * authentication/*from www . j a va 2s. c o m*/ * @param sslTrustAll Whether to trust all SSL certificates * @param sslTrustkey A specific SSL key to accept exclusively * @param timeout The connection timeout for all requests * @param authAddress The authentication domain address * @param authPort The authentication domain port number * @return An HttpClient that should be stored locally and reused for every new request * @throws DaemonException Thrown when information (such as username/password) is missing */ public static DefaultHttpClient createStandardHttpClient(boolean userBasicAuth, String username, String password, boolean sslTrustAll, String sslTrustkey, int timeout, String authAddress, int authPort) throws DaemonException { // Register http and https sockets SchemeRegistry registry = new SchemeRegistry(); registry.register(new Scheme("http", new PlainSocketFactory(), 80)); SocketFactory https_socket = sslTrustAll ? new FakeSocketFactory() : sslTrustkey != null ? new FakeSocketFactory(sslTrustkey) : SSLSocketFactory.getSocketFactory(); registry.register(new Scheme("https", https_socket, 443)); // Standard parameters HttpParams httpparams = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpparams, timeout); HttpConnectionParams.setSoTimeout(httpparams, timeout); if (userAgent != null) { HttpProtocolParams.setUserAgent(httpparams, userAgent); } DefaultHttpClient httpclient = new DefaultHttpClient(new ThreadSafeClientConnManager(httpparams, registry), httpparams); // Authentication credentials if (userBasicAuth) { if (username == null || password == null) { throw new DaemonException(ExceptionType.AuthenticationFailure, "No username or password was provided while we hadauthentication enabled"); } httpclient.getCredentialsProvider().setCredentials( new AuthScope(authAddress, authPort, AuthScope.ANY_REALM), new UsernamePasswordCredentials(username, password)); } return httpclient; }
From source file:com.vodafone360.people.service.transport.http.HttpConnectionThread.java
/** * Sets HTTP settings./* ww w. j a v a 2 s .c o m*/ */ public void setHttpClient() { int connectionTimeout = Settings.HTTP_CONNECTION_TIMEOUT; HttpParams myHttpParams = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(myHttpParams, connectionTimeout); HttpConnectionParams.setSoTimeout(myHttpParams, connectionTimeout); mHttpClient = new DefaultHttpClient(myHttpParams); // get http }
From source file:dictinsight.utils.io.HttpUtils.java
public static boolean postData(String[] keys, String[] values) { DefaultHttpClient client = new DefaultHttpClient(); HttpParams params = client.getParams(); HttpConnectionParams.setSoTimeout(params, 1000 * 60); HttpConnectionParams.setConnectionTimeout(params, 1000 * 5); if (null == SEND_MESSAGE_URL) SEND_MESSAGE_URL = FileUtils.getStringConfig("course-server.conf", "pushHost", "http://livetest.youdao.com/pushMsgSingle"); HttpPost post = new HttpPost(SEND_MESSAGE_URL); try {//from w w w .j a v a 2 s .co m List<NameValuePair> nvps = new ArrayList<NameValuePair>(); if (keys != null && values != null) { if (keys.length != values.length) { return false; } else { for (int i = 0; i < keys.length; i++) { nvps.add(new BasicNameValuePair(keys[i], values[i])); } } } post.setEntity(new UrlEncodedFormEntity(nvps)); HttpResponse response = client.execute(post); int code = response.getStatusLine().getStatusCode(); if (code == HttpStatus.SC_OK) { String strResult = EntityUtils.toString(response.getEntity()); JSONObject result = JSONObject.parseObject(strResult); if (result == null) { return false; } int suc = result.getIntValue(SUCCESS); return suc == 1; } } catch (Exception e) { e.printStackTrace(); } finally { post.releaseConnection(); } return false; }
From source file:com.amazonaws.http.HttpClientFactory.java
/** * Creates a new HttpClient object using the specified AWS * ClientConfiguration to configure the client. * * @param config/*from www .j a v a 2 s. c o m*/ * Client configuration options (ex: proxy settings, connection * limits, etc). * * @return The new, configured HttpClient. */ public HttpClient createHttpClient(ClientConfiguration config) { /* Set HTTP client parameters */ HttpParams httpClientParams = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpClientParams, config.getConnectionTimeout()); HttpConnectionParams.setSoTimeout(httpClientParams, config.getSocketTimeout()); HttpConnectionParams.setStaleCheckingEnabled(httpClientParams, true); HttpConnectionParams.setTcpNoDelay(httpClientParams, true); HttpConnectionParams.setSoKeepalive(httpClientParams, config.useTcpKeepAlive()); int socketSendBufferSizeHint = config.getSocketBufferSizeHints()[0]; int socketReceiveBufferSizeHint = config.getSocketBufferSizeHints()[1]; if (socketSendBufferSizeHint > 0 || socketReceiveBufferSizeHint > 0) { HttpConnectionParams.setSocketBufferSize(httpClientParams, Math.max(socketSendBufferSizeHint, socketReceiveBufferSizeHint)); } final SSLContext sslContext = createSSLContext(config); SSLSocketFactory sslSocketFactory = config.getApacheHttpClientConfig().getSslSocketFactory(); if (sslSocketFactory == null) { sslSocketFactory = new SdkTLSSocketFactory(sslContext, SSLSocketFactory.STRICT_HOSTNAME_VERIFIER); } PoolingClientConnectionManager connectionManager = ConnectionManagerFactory .createPoolingClientConnManager(config, httpClientParams, sslSocketFactory); SdkHttpClient httpClient = new SdkHttpClient(connectionManager, httpClientParams); httpClient.setHttpRequestRetryHandler(HttpRequestNoRetryHandler.Singleton); httpClient.setRedirectStrategy(new NeverFollowRedirectStrategy()); if (config.getConnectionMaxIdleMillis() > 0) { httpClient .setKeepAliveStrategy(new SdkConnectionKeepAliveStrategy(config.getConnectionMaxIdleMillis())); } if (config.getLocalAddress() != null) { ConnRouteParams.setLocalAddress(httpClientParams, config.getLocalAddress()); } Scheme http = new Scheme("http", 80, PlainSocketFactory.getSocketFactory()); Scheme https = new Scheme("https", 443, sslSocketFactory); SchemeRegistry sr = connectionManager.getSchemeRegistry(); sr.register(http); sr.register(https); /* * If SSL cert checking for endpoints has been explicitly disabled, * register a new scheme for HTTPS that won't cause self-signed certs to * error out. */ if (System.getProperty(DISABLE_CERT_CHECKING_SYSTEM_PROPERTY) != null) { Scheme sch = new Scheme("https", 443, new TrustingSocketFactory()); httpClient.getConnectionManager().getSchemeRegistry().register(sch); } /* Set proxy if configured */ String proxyHost = config.getProxyHost(); int proxyPort = config.getProxyPort(); if (proxyHost != null && proxyPort > 0) { AmazonHttpClient.log .info("Configuring Proxy. Proxy Host: " + proxyHost + " " + "Proxy Port: " + proxyPort); HttpHost proxyHttpHost = new HttpHost(proxyHost, proxyPort); httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxyHttpHost); String proxyUsername = config.getProxyUsername(); String proxyPassword = config.getProxyPassword(); String proxyDomain = config.getProxyDomain(); String proxyWorkstation = config.getProxyWorkstation(); if (proxyUsername != null && proxyPassword != null) { httpClient.getCredentialsProvider().setCredentials(new AuthScope(proxyHost, proxyPort), new NTCredentials(proxyUsername, proxyPassword, proxyWorkstation, proxyDomain)); } // Add a request interceptor that sets up proxy authentication pre-emptively if configured if (config.isPreemptiveBasicProxyAuth()) { httpClient.addRequestInterceptor(new PreemptiveProxyAuth(proxyHttpHost), 0); } } /* Accept Gzip response if configured */ if (config.useGzip()) { httpClient.addRequestInterceptor(new HttpRequestInterceptor() { @Override 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() { @Override public void process(final HttpResponse response, final HttpContext context) throws HttpException, IOException { HttpEntity entity = response.getEntity(); if (entity != null) { Header ceheader = entity.getContentEncoding(); if (ceheader != null) { HeaderElement[] codecs = ceheader.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:com.android.mms.service.http.NetworkAwareHttpClient.java
/** * Create a new HttpClient with reasonable defaults (which you can update). * * @param userAgent to report in your HTTP requests * @param context to use for caching SSL sessions (may be null for no caching) * @return AndroidHttpClient for you to use for all your requests. *//*from ww w .ja v a2 s . c o m*/ public static NetworkAwareHttpClient newInstance(String userAgent, Context context, NameResolver resolver, boolean shouldUseIpv6) { HttpParams params = new BasicHttpParams(); // Turn off stale checking. Our connections break all the time anyway, // and it's not worth it to pay the penalty of checking every time. HttpConnectionParams.setStaleCheckingEnabled(params, false); HttpConnectionParams.setConnectionTimeout(params, SOCKET_OPERATION_TIMEOUT); HttpConnectionParams.setSoTimeout(params, SOCKET_OPERATION_TIMEOUT); HttpConnectionParams.setSocketBufferSize(params, 8192); // Don't handle redirects -- return them to the caller. Our code // often wants to re-POST after a redirect, which we must do ourselves. HttpClientParams.setRedirecting(params, false); // Use a session cache for SSL sockets SSLSessionCache sessionCache = context == null ? null : new SSLSessionCache(context); // Set the specified user agent and register standard protocols. HttpProtocolParams.setUserAgent(params, userAgent); SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); schemeRegistry.register(new Scheme("https", SSLCertificateSocketFactory.getHttpSocketFactory(SOCKET_OPERATION_TIMEOUT, sessionCache), 443)); /* * CHANGE FOR MmsService: using a different ClientConnectionManager which * uses a custom name resolver and can specify address type */ ClientConnectionManager manager = new NetworkAwareThreadSafeClientConnManager(params, schemeRegistry, resolver, shouldUseIpv6); // We use a factory method to modify superclass initialization // parameters without the funny call-a-static-method dance. return new NetworkAwareHttpClient(manager, params); }