List of usage examples for org.apache.http.params BasicHttpParams BasicHttpParams
public BasicHttpParams()
From source file:com.jug6ernaut.android.utilites.FileDownloader.java
/** * still has issues...// w w w . j a va 2 s. c o m * * @param inputUrl * @param outputFile * @return */ @Deprecated public File downloadFileNew(File inputUrl, File outputFile) { OutputStream out = null; InputStream fis = null; HttpParams httpParameters = new BasicHttpParams(); int timeoutConnection = 2500; HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection); int timeoutSocket = 2500; HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket); File dir = outputFile.getParentFile(); dir.mkdirs(); try { HttpGet httpRequest = new HttpGet(stringFromFile(inputUrl)); DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters); HttpResponse response = httpClient.execute(httpRequest); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode == HttpStatus.SC_OK) { HttpEntity entity = response.getEntity(); out = new BufferedOutputStream(new FileOutputStream(outputFile)); long total = entity.getContentLength(); fis = entity.getContent(); if (total > 1 || true) startTalker(total); else { throw new IOException("Content null"); } long progress = 0; byte[] buffer = new byte[1024]; int length = 0; while ((length = fis.read(buffer)) != -1) { out.write(buffer, 0, length); progressTalker(length); progress += length; } /* for (int b; (b = fis.read()) != -1;) { out.write(b); progress+=b; progressTalker(b); } */ finishTalker(progress); } } catch (Exception e) { cancelTalker(e); e.printStackTrace(); return null; } finally { try { if (out != null) { out.flush(); out.close(); } if (fis != null) fis.close(); } catch (IOException e) { e.printStackTrace(); } } return outputFile; }
From source file:com.globalsight.everest.tda.TdaHelper.java
public String loginCheck(String hostName, String userName, String password) { int timeoutConnection = 8000; HttpParams httpParameters = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection); DefaultHttpClient httpclient = new DefaultHttpClient(httpParameters); String loginUrl = new String(); String errorInfo = new String(); hostName = hostName.trim();/*from w w w . ja v a 2s . com*/ userName = userName.trim(); if (hostName.indexOf("http://") < 0) { loginUrl = "http://" + hostName; } else { loginUrl = hostName; } if (hostName.lastIndexOf("/") == (hostName.length() - 1)) { loginUrl = loginUrl + "auth_key.json?action=login"; } else { loginUrl = loginUrl + "/auth_key.json?action=login"; } try { HttpPost httpost = new HttpPost(loginUrl); MultipartEntity reqEntity = new MultipartEntity(); StringBody nameBody = new StringBody(userName); StringBody passwordBody = new StringBody(password); StringBody appKeyBody = new StringBody(appKey); reqEntity.addPart("auth_username", nameBody); reqEntity.addPart("auth_password", passwordBody); reqEntity.addPart("auth_app_key", appKeyBody); httpost.setEntity(reqEntity); HttpResponse response = httpclient.execute(httpost); StatusLine sl = response.getStatusLine(); if (sl.getStatusCode() == 404) { errorInfo = "The TDA URL is not correct."; } else if (sl.getStatusCode() == 401) { errorInfo = "The username and password given are not a valid TDA login."; } else if (sl.getStatusCode() == 201) { errorInfo = "ture"; } else { errorInfo = "The TDA configuration is not correct!"; } } catch (Exception e) { s_logger.info("Can not connect TDA server:" + e.getMessage()); errorInfo = "Can not connect TDA server."; } return errorInfo; }
From source file:com.applicake.beanstalkclient.utils.AndroidHttpClient.java
/** * Create a new HttpClient with reasonable defaults (which you can update). * // ww w .java2s . c om * @param userAgent * to report in your HTTP requests. * @param sessionCache * persistent session cache * @return AndroidHttpClient for you to use for all your requests. */ public static AndroidHttpClient newInstance(String userAgent) { 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, 20 * 1000); HttpConnectionParams.setSoTimeout(params, 20 * 1000); 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); // 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:com.dmbstream.android.service.RESTMusicService.java
public RESTMusicService() { // Create and initialize default HTTP parameters HttpParams params = new BasicHttpParams(); ConnManagerParams.setMaxTotalConnections(params, 20); ConnManagerParams.setMaxConnectionsPerRoute(params, new ConnPerRouteBean(20)); HttpConnectionParams.setConnectionTimeout(params, SOCKET_CONNECT_TIMEOUT); HttpConnectionParams.setSoTimeout(params, SOCKET_READ_TIMEOUT_DEFAULT); // 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); // Create and initialize scheme registry SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); // Create an HttpClient with the ThreadSafeClientConnManager. // This connection manager must be used if more than one thread will // be using the HttpClient. connManager = new ThreadSafeClientConnManager(params, schemeRegistry); httpClient = new DefaultHttpClient(connManager, params); }
From source file:com.cloudkick.CloudkickAPI.java
public CloudkickAPI(Context context) throws EmptyCredentialsException { prefs = PreferenceManager.getDefaultSharedPreferences(context); key = prefs.getString("editKey", ""); secret = prefs.getString("editSecret", ""); if (key == "" || secret == "") { throw new EmptyCredentialsException(); }/*from w w w. j av a2 s . c om*/ HttpParams params = new BasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, HTTP.DEFAULT_CONTENT_CHARSET); HttpProtocolParams.setUseExpectContinue(params, true); SchemeRegistry registry = new SchemeRegistry(); registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); registry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443)); ClientConnectionManager connman = new ThreadSafeClientConnManager(params, registry); client = new DefaultHttpClient(connman, params); }
From source file:org.wso2.emm.agent.proxy.clients.OAuthSSLClient.java
@Override public HttpClient getHttpClient() throws IDPTokenManagerException { HttpClient client = null;/*from w w w .j av a 2s . co m*/ InputStream inStream = null; try { if (Constants.SERVER_PROTOCOL.equalsIgnoreCase("https://")) { KeyStore localTrustStore = KeyStore.getInstance("BKS"); inStream = IdentityProxy.getInstance().getContext().getResources().openRawResource(R.raw.trust); localTrustStore.load(inStream, Constants.TRUSTSTORE_PASSWORD.toCharArray()); SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), Constants.HTTP)); SSLSocketFactory sslSocketFactory = new SSLSocketFactory(localTrustStore); sslSocketFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); schemeRegistry.register(new Scheme("https", sslSocketFactory, Constants.HTTPS)); HttpParams params = new BasicHttpParams(); ClientConnectionManager connectionManager = new ThreadSafeClientConnManager(params, schemeRegistry); client = new DefaultHttpClient(connectionManager, params); } else { client = new DefaultHttpClient(); } } catch (KeyStoreException e) { String errorMsg = "Error occurred while accessing keystore."; Log.e(TAG, errorMsg); throw new IDPTokenManagerException(errorMsg, e); } catch (CertificateException e) { String errorMsg = "Error occurred while loading certificate."; Log.e(TAG, errorMsg); throw new IDPTokenManagerException(errorMsg, e); } catch (NoSuchAlgorithmException e) { String errorMsg = "Error occurred while due to mismatch of defined algorithm."; Log.e(TAG, errorMsg); throw new IDPTokenManagerException(errorMsg, e); } catch (UnrecoverableKeyException e) { String errorMsg = "Error occurred while accessing keystore."; Log.e(TAG, errorMsg); throw new IDPTokenManagerException(errorMsg, e); } catch (KeyManagementException e) { String errorMsg = "Error occurred while accessing keystore."; Log.e(TAG, errorMsg); throw new IDPTokenManagerException(errorMsg, e); } catch (IOException e) { String errorMsg = "Error occurred while loading trust store. "; Log.e(TAG, errorMsg); throw new IDPTokenManagerException(errorMsg, e); } finally { StreamHandlerUtil.closeInputStream(inStream, TAG); } return client; }
From source file:com.aretha.net.HttpConnectionHelper.java
private HttpConnectionHelper() { HttpParams params = mParams = new BasicHttpParams(); ConnManagerParams.setMaxTotalConnections(params, MAX_CONNECTION_NUMBER); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443)); /**//from ww w . j a v a 2 s . c om * android SDK not support MultiThreadedHttpConnectionManager * temporarily, so use the {@link ThreadSafeClientConnManager} instead */ ThreadSafeClientConnManager threadSafeClientConnManager = new ThreadSafeClientConnManager(params, schemeRegistry); HttpConnectionParams.setConnectionTimeout(params, DEFAULT_CONNECTION_TIMEOUT * SECOND_IN_MILLIS); HttpConnectionParams.setSoTimeout(params, DEFAULT_CONNECTION_TIMEOUT * SECOND_IN_MILLIS); HttpConnectionParams.setSocketBufferSize(params, 8192); mHttpClient = new DefaultHttpClient(threadSafeClientConnManager, params); mHttpClient.addRequestInterceptor(this); mHttpClient.addResponseInterceptor(this); mCookieStore = mHttpClient.getCookieStore(); }
From source file:com.nirima.jenkins.SimpleArtifactCopier.java
private void init() throws URISyntaxException { URI targetURI = host.toURI(); targetHost = new HttpHost(targetURI.getHost(), targetURI.getPort()); params = new BasicHttpParams(); params.setParameter(HttpProtocolParams.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); params.setBooleanParameter(HttpProtocolParams.USE_EXPECT_CONTINUE, false); params.setBooleanParameter(HttpConnectionParams.STALE_CONNECTION_CHECK, false); params.setIntParameter(HttpConnectionParams.SOCKET_BUFFER_SIZE, 8 * 1024); httpexecutor = new HttpRequestExecutor(); httpproc = new BasicHttpProcessor(); // Required protocol interceptors httpproc.addInterceptor(new RequestContent()); httpproc.addInterceptor(new RequestTargetHost()); // Recommended protocol interceptors httpproc.addInterceptor(new RequestConnControl()); httpproc.addInterceptor(new RequestUserAgent()); httpproc.addInterceptor(new RequestExpectContinue()); context = new BasicHttpContext(); conn = new DefaultHttpClientConnection(); connStrategy = new DefaultConnectionReuseStrategy(); }
From source file:de.huxhorn.whistler.services.JmpUrlShortener.java
public String shorten(String url) { List<NameValuePair> qparams = new ArrayList<NameValuePair>(); // http://api.bit.ly/shorten?version=2.0.1&longUrl=http://cnn.com&login=bitlyapidemo&apiKey=R_0da49e0a9118ff35f52f629d2d71bf07 qparams.add(new BasicNameValuePair("version", "2.0.1")); qparams.add(new BasicNameValuePair("longUrl", url)); if (login != null) { qparams.add(new BasicNameValuePair("login", login)); qparams.add(new BasicNameValuePair("apiKey", apiKey)); qparams.add(new BasicNameValuePair("history", "1")); }/*from w w w.j ava2s . c om*/ try { BasicHttpParams params = new BasicHttpParams(); /*params.setParameter(CookieSpecPNames.DATE_PATTERNS, Arrays.asList("EEE, dd-MMM-yyyy HH:mm:ss z", "EEE, dd MMM yyyy HH:mm:ss z")); params.setParameter( ClientPNames.COOKIE_POLICY, CookiePolicy.BEST_MATCH); BestMatchSpecFactory factory = new BestMatchSpecFactory(); CookieSpec cookiespec = factory.newInstance(params); */ DefaultHttpClient httpclient = new DefaultHttpClient(params); //httpclient.setCookieSpecs(cookiespec); //BestMatchSpecFactory factory = new BestMatchSpecFactory(); //CookieSpec cookiespec = factory.newInstance(params); //BasicHeader header = new BasicHeader("Set-Cookie", // "asid=011e7014f5e7718e02d893335aa5a16e; path=/; " + // "expires=Wed, 16-May-2018 17:13:32 GMT"); //CookieOrigin origin = new CookieOrigin("localhost", 80, "/", false); //List<Cookie> cookies = cookiespec.parse(header, origin); //System.out.println(cookies); // TODO: Cookie spec URI uri = URIUtils.createURI("http", "api.j.mp", -1, "/shorten", URLEncodedUtils.format(qparams, "UTF-8"), null); HttpGet httpget = new HttpGet(uri); if (logger.isDebugEnabled()) logger.debug("HttpGet.uri={}", httpget.getURI()); HttpResponse response = httpclient.execute(httpget); HttpEntity entity = response.getEntity(); if (entity != null) { InputStream instream = entity.getContent(); JsonFactory f = new JsonFactory(); JsonParser jp = f.createJsonParser(instream); JmpShortenResponse responseObj = new JmpShortenResponse(); for (;;) { JsonToken token = jp.nextToken(); String fieldname = jp.getCurrentName(); if (logger.isDebugEnabled()) logger.debug("Token={}, currentName={}", token, fieldname); if (token == JsonToken.START_OBJECT) { continue; } if (token == JsonToken.END_OBJECT) { break; } if ("errorCode".equals(fieldname)) { token = jp.nextToken(); responseObj.setErrorCode(jp.getIntValue()); } else if ("errorMessage".equals(fieldname)) { token = jp.nextToken(); responseObj.setErrorMessage(jp.getText()); } else if ("statusCode".equals(fieldname)) { token = jp.nextToken(); responseObj.setStatusCode(jp.getText()); } else if ("results".equals(fieldname)) { // contains an object Map<String, ShortenedUrl> results = parseResults(jp); responseObj.setResults(results); } else { throw new IllegalStateException("Unrecognized field '" + fieldname + "'!"); } } Map<String, ShortenedUrl> results = responseObj.getResults(); if (results == null) { return null; } ShortenedUrl shortened = results.get(url); if (shortened == null) { return null; } if (logger.isDebugEnabled()) logger.debug("JmpShortenResponse: {}", responseObj); if ("OK".equals(responseObj.getStatusCode())) { return shortened.getShortUrl(); } // TODO: better error handling if (logger.isWarnEnabled()) logger.warn("JmpShortenResponse: {}", responseObj); } } catch (IOException ex) { if (logger.isWarnEnabled()) logger.warn("Exception!", ex); } catch (URISyntaxException ex) { if (logger.isWarnEnabled()) logger.warn("Exception!", ex); } // catch (MalformedCookieException ex) // { // if (logger.isWarnEnabled()) logger.warn("Exception!", ex); // } return null; }
From source file:cn.ctyun.amazonaws.http.HttpClientFactory.java
/** * Creates a new HttpClient object using the specified AWS * ClientConfiguration to configure the client. * * @param config// w ww . java 2s . 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); int socketSendBufferSizeHint = config.getSocketBufferSizeHints()[0]; int socketReceiveBufferSizeHint = config.getSocketBufferSizeHints()[1]; if (socketSendBufferSizeHint > 0 || socketReceiveBufferSizeHint > 0) { HttpConnectionParams.setSocketBufferSize(httpClientParams, Math.max(socketSendBufferSizeHint, socketReceiveBufferSizeHint)); } /* Set connection manager */ ThreadSafeClientConnManager connectionManager = ConnectionManagerFactory .createThreadSafeClientConnManager(config, httpClientParams); DefaultHttpClient httpClient = new DefaultHttpClient(connectionManager, httpClientParams); httpClient.setRedirectStrategy(new LocationHeaderNotRequiredRedirectStrategy()); try { Scheme http = new Scheme("http", 80, PlainSocketFactory.getSocketFactory()); SSLSocketFactory sf = new SSLSocketFactory(SSLContext.getDefault(), SSLSocketFactory.STRICT_HOSTNAME_VERIFIER); Scheme https = new Scheme("https", 443, sf); SchemeRegistry sr = connectionManager.getSchemeRegistry(); sr.register(http); sr.register(https); } catch (NoSuchAlgorithmException e) { throw new AmazonClientException("Unable to access default SSL context", e); } /* * 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("com.amazonaws.sdk.disableCertChecking") != 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)); } } return httpClient; }