List of usage examples for org.apache.http.params BasicHttpParams BasicHttpParams
public BasicHttpParams()
From source file:org.jfrog.build.client.PreemptiveHttpClient.java
private DefaultHttpClient createHttpClient(String userName, String password, int timeout) { BasicHttpParams params = new BasicHttpParams(); int timeoutMilliSeconds = timeout * 1000; HttpConnectionParams.setConnectionTimeout(params, timeoutMilliSeconds); HttpConnectionParams.setSoTimeout(params, timeoutMilliSeconds); DefaultHttpClient client = new DefaultHttpClient(params); if (userName != null && !"".equals(userName)) { client.getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), new UsernamePasswordCredentials(userName, password)); localContext = new BasicHttpContext(); // Generate BASIC scheme object and stick it to the local execution context BasicScheme basicAuth = new BasicScheme(); localContext.setAttribute("preemptive-auth", basicAuth); // Add as the first request interceptor client.addRequestInterceptor(new PreemptiveAuth(), 0); }/*from www. ja v a 2 s.c o m*/ boolean requestSentRetryEnabled = Boolean.parseBoolean(System.getProperty("requestSentRetryEnabled")); if (requestSentRetryEnabled) { client.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler(3, requestSentRetryEnabled)); } // set the following user agent with each request String userAgent = "ArtifactoryBuildClient/" + CLIENT_VERSION; HttpProtocolParams.setUserAgent(client.getParams(), userAgent); return client; }
From source file:com.lgallardo.qbittorrentclient.RSSFeedParser.java
public RSSFeed getRSSFeed(String channelTitle, String channelUrl, String filter) { // Decode url link try {/* ww w . j a v a 2 s . c o m*/ channelUrl = URLDecoder.decode(channelUrl, "UTF-8"); } catch (UnsupportedEncodingException e) { Log.e("Debug", "RSSFeedParser - decoding error: " + e.toString()); } // Parse url Uri uri = uri = Uri.parse(channelUrl); ; int event; String text = null; String torrent = null; boolean header = true; // TODO delete itemCount, as it's not really used this.itemCount = 0; HttpResponse httpResponse; DefaultHttpClient httpclient; XmlPullParserFactory xmlFactoryObject; XmlPullParser xmlParser = null; HttpParams httpParameters = new BasicHttpParams(); // Set the timeout in milliseconds until a connection is established. // The default value is zero, that means the timeout is not used. int timeoutConnection = connection_timeout * 1000; // Set the default socket timeout (SO_TIMEOUT) // in milliseconds which is the timeout for waiting for data. int timeoutSocket = data_timeout * 1000; // Set http parameters HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection); HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket); HttpProtocolParams.setUserAgent(httpParameters, "qBittorrent for Android"); HttpProtocolParams.setVersion(httpParameters, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(httpParameters, HTTP.UTF_8); RSSFeed rssFeed = new RSSFeed(); rssFeed.setChannelTitle(channelTitle); rssFeed.setChannelLink(channelUrl); httpclient = null; try { // Making HTTP request HttpHost targetHost = new HttpHost(uri.getAuthority()); // httpclient = new DefaultHttpClient(httpParameters); // httpclient = new DefaultHttpClient(); httpclient = getNewHttpClient(); httpclient.setParams(httpParameters); // AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort()); // UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(this.username, this.password); // // httpclient.getCredentialsProvider().setCredentials(authScope, credentials); // set http parameters HttpGet httpget = new HttpGet(channelUrl); httpResponse = httpclient.execute(targetHost, httpget); StatusLine statusLine = httpResponse.getStatusLine(); int mStatusCode = statusLine.getStatusCode(); if (mStatusCode != 200) { httpclient.getConnectionManager().shutdown(); throw new JSONParserStatusCodeException(mStatusCode); } HttpEntity httpEntity = httpResponse.getEntity(); is = httpEntity.getContent(); xmlFactoryObject = XmlPullParserFactory.newInstance(); xmlParser = xmlFactoryObject.newPullParser(); xmlParser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false); xmlParser.setInput(is, null); event = xmlParser.getEventType(); // Get Channel info String name; RSSFeedItem item = null; ArrayList<RSSFeedItem> items = new ArrayList<RSSFeedItem>(); // Get items while (event != XmlPullParser.END_DOCUMENT) { name = xmlParser.getName(); switch (event) { case XmlPullParser.START_TAG: if (name != null && name.equals("item")) { header = false; item = new RSSFeedItem(); itemCount = itemCount + 1; } try { for (int i = 0; i < xmlParser.getAttributeCount(); i++) { if (xmlParser.getAttributeName(i).equals("url")) { torrent = xmlParser.getAttributeValue(i); if (torrent != null) { torrent = Uri.decode(URLEncoder.encode(torrent, "UTF-8")); } break; } } } catch (Exception e) { } break; case XmlPullParser.TEXT: text = xmlParser.getText(); break; case XmlPullParser.END_TAG: if (name.equals("title")) { if (!header) { item.setTitle(text); // Log.d("Debug", "PARSER - Title: " + text); } } else if (name.equals("description")) { if (header) { // Log.d("Debug", "Channel Description: " + text); } else { item.setDescription(text); // Log.d("Debug", "Description: " + text); } } else if (name.equals("link")) { if (!header) { item.setLink(text); // Log.d("Debug", "Link: " + text); } } else if (name.equals("pubDate")) { // Set item pubDate if (item != null) { item.setPubDate(text); } } else if (name.equals("enclosure")) { item.setTorrentUrl(torrent); // Log.d("Debug", "Enclosure: " + torrent); } else if (name.equals("item") && !header) { if (items != null & item != null) { // Fix torrent url for no-standard rss feeds if (torrent == null) { String link = item.getLink(); if (link != null) { link = Uri.decode(URLEncoder.encode(link, "UTF-8")); } item.setTorrentUrl(link); } items.add(item); } } break; } event = xmlParser.next(); // if (!header) { // items.add(item); // } } // Filter items // Log.e("Debug", "RSSFeedParser - filter: >" + filter + "<"); if (filter != null && !filter.equals("")) { Iterator iterator = items.iterator(); while (iterator.hasNext()) { item = (RSSFeedItem) iterator.next(); // If link doesn't match filter, remove it // Log.e("Debug", "RSSFeedParser - item no filter: >" + item.getTitle() + "<"); Pattern patter = Pattern.compile(filter); Matcher matcher = patter.matcher(item.getTitle()); // get a matcher object if (!(matcher.find())) { iterator.remove(); } } } rssFeed.setItems(items); rssFeed.setItemCount(itemCount); rssFeed.setChannelPubDate(items.get(0).getPubDate()); rssFeed.setResultOk(true); is.close(); } catch (Exception e) { Log.e("Debug", "RSSFeedParser - : " + e.toString()); rssFeed.setResultOk(false); } finally { // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources if (httpclient != null) { httpclient.getConnectionManager().shutdown(); } } // return JSON String return rssFeed; }
From source file:me.xiaopan.android.gohttp.HttpClientManager.java
public HttpClientManager(SchemeRegistry schemeRegistry) { BasicHttpParams httpParams = new BasicHttpParams(); HttpConnectionParams.setTcpNoDelay(httpParams, true); //?TCP HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1); //Http?? HttpProtocolParams.setUserAgent(httpParams, DEFAULT_USER_AGENT); //? httpContext = new SyncBasicHttpContext(new BasicHttpContext()); //?Http httpClient = new DefaultHttpClient(new ThreadSafeClientConnManager(httpParams, schemeRegistry), httpParams); httpClient.addRequestInterceptor(new GzipProcessRequestInterceptor()); httpClient.addRequestInterceptor(new AddRequestHeaderRequestInterceptor(getHeaderMap())); httpClient.addResponseInterceptor(new GzipProcessResponseInterceptor()); httpClient/* ww w. j a v a 2 s . c o m*/ .setHttpRequestRetryHandler(new RetryHandler(DEFAULT_MAX_RETRIES, DEFAULT_RETRY_SLEEP_TIME_MILLIS)); clientHeaderMap = new HashMap<String, String>(); setTimeout(DEFAULT_TIMEOUT); setMaxConnections(DEFAULT_MAX_CONNECTIONS); setSocketBufferSize(DEFAULT_SOCKET_BUFFER_SIZE); }
From source file:fast.simple.download.http.DownloadHttpClient.java
/** * Create a new HttpClient with reasonable defaults (which you can update). * /*from w w w . j av a2 s. c om*/ * @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. */ public static DownloadHttpClient 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); 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, true); // 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)); 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 DownloadHttpClient(manager, params); }
From source file:ch.cyberduck.core.http.HttpSession.java
protected AbstractHttpClient http(final String hostname) { if (!clients.containsKey(hostname)) { final HttpParams params = new BasicHttpParams(); HttpProtocolParams.setVersion(params, org.apache.http.HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, getEncoding()); HttpProtocolParams.setUserAgent(params, getUserAgent()); AuthParams.setCredentialCharset(params, Preferences.instance().getProperty("http.credentials.charset")); HttpConnectionParams.setTcpNoDelay(params, true); HttpConnectionParams.setSoTimeout(params, timeout()); HttpConnectionParams.setConnectionTimeout(params, timeout()); HttpConnectionParams.setSocketBufferSize(params, Preferences.instance().getInteger("http.socket.buffer")); HttpConnectionParams.setStaleCheckingEnabled(params, true); HttpClientParams.setRedirecting(params, true); HttpClientParams.setAuthenticating(params, true); HttpClientParams.setCookiePolicy(params, CookiePolicy.BEST_MATCH); // Sets the timeout in milliseconds used when retrieving a connection from the ClientConnectionManager HttpClientParams.setConnectionManagerTimeout(params, Preferences.instance().getLong("http.manager.timeout")); SchemeRegistry registry = new SchemeRegistry(); // Always register HTTP for possible use with proxy registry.register(new Scheme(ch.cyberduck.core.Scheme.http.toString(), host.getPort(), PlainSocketFactory.getSocketFactory())); registry.register(new Scheme(ch.cyberduck.core.Scheme.https.toString(), host.getPort(), new SSLSocketFactory( new CustomTrustSSLProtocolSocketFactory(this.getTrustManager()).getSSLContext(), new X509HostnameVerifier() { @Override public void verify(String host, SSLSocket ssl) throws IOException { log.warn("Hostname verification disabled for:" + host); }//from w w w . jav a 2 s . co m @Override public void verify(String host, X509Certificate cert) throws SSLException { log.warn("Hostname verification disabled for:" + host); } @Override public void verify(String host, String[] cns, String[] subjectAlts) throws SSLException { log.warn("Hostname verification disabled for:" + host); } @Override public boolean verify(String s, javax.net.ssl.SSLSession sslSession) { log.warn("Hostname verification disabled for:" + s); return true; } }))); if (Preferences.instance().getBoolean("connection.proxy.enable")) { final Proxy proxy = ProxyFactory.get(); if (ch.cyberduck.core.Scheme.https.equals(this.getHost().getProtocol().getScheme())) { if (proxy.isHTTPSProxyEnabled(host)) { ConnRouteParams.setDefaultProxy(params, new HttpHost(proxy.getHTTPSProxyHost(host), proxy.getHTTPSProxyPort(host))); } } if (ch.cyberduck.core.Scheme.http.equals(this.getHost().getProtocol().getScheme())) { if (proxy.isHTTPProxyEnabled(host)) { ConnRouteParams.setDefaultProxy(params, new HttpHost(proxy.getHTTPProxyHost(host), proxy.getHTTPProxyPort(host))); } } } PoolingClientConnectionManager manager = new PoolingClientConnectionManager(registry); manager.setMaxTotal(Preferences.instance().getInteger("http.connections.total")); manager.setDefaultMaxPerRoute(Preferences.instance().getInteger("http.connections.route")); AbstractHttpClient http = new DefaultHttpClient(manager, params); this.configure(http); clients.put(hostname, http); } return clients.get(hostname); }
From source file:com.rackspacecloud.client.service_registry.clients.BaseClient.java
public BaseClient(AuthClient authClient, String apiUrl) { this(new DefaultHttpClient() { protected HttpParams createHttpParams() { BasicHttpParams params = new BasicHttpParams(); org.apache.http.params.HttpConnectionParams.setSoTimeout(params, 10000); params.setParameter("http.socket.timeout", 10000); return params; }/*from w ww .j a v a2 s .c om*/ @Override protected ClientConnectionManager createClientConnectionManager() { SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory())); schemeRegistry.register(new Scheme("https", 443, SSLSocketFactory.getSocketFactory())); return new ThreadSafeClientConnManager(createHttpParams(), schemeRegistry); } }, authClient, apiUrl); }
From source file:org.iglootools.hchelpers.core.DefaultHttpClientFactory.java
public static BasicHttpParams httpParams(Map<String, Object> params) { BasicHttpParams httpParams = new BasicHttpParams(); for (Entry<String, Object> e : params.entrySet()) { httpParams.setParameter(e.getKey(), e.getValue()); }/*from w w w. j a v a2 s. c om*/ return httpParams; }
From source file:com.wentam.defcol.connect_to_computer.WebServer.java
public void runServer() { try {/*from w w w.j a v a 2s . c om*/ serverSocket = new ServerSocket(serverPort); serverSocket.setReuseAddress(true); while (running) { try { final Socket socket = serverSocket.accept(); DefaultHttpServerConnection serverConnection = new DefaultHttpServerConnection(); serverConnection.bind(socket, new BasicHttpParams()); httpService.handleRequest(serverConnection, httpContext); serverConnection.shutdown(); } catch (IOException e) { e.printStackTrace(); } catch (HttpException e) { e.printStackTrace(); } } serverSocket.close(); } catch (SocketException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } running = false; }
From source file:com.riksof.a320.http.CoreHttpClient.java
/** * This method is used to execute Get Http Request * /*from w w w . j ava 2 s . c o m*/ * @param url * @return * @throws ServerException */ public String executeGet(String url) throws ServerException { // Response String String responseString = null; headers = new HashMap<String, String>(); try { CacheConfig cacheConfig = new CacheConfig(); cacheConfig.setMaxCacheEntries(1000); cacheConfig.setMaxObjectSizeBytes(1024 * 1024); HttpParams httpParameters = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpParameters, connectionTimeOut); HttpConnectionParams.setSoTimeout(httpParameters, socketTimeOut); // Create http client object DefaultHttpClient realClient = new DefaultHttpClient(httpParameters); realClient.addResponseInterceptor(MakeCacheable.INSTANCE, 0); CachingHttpClient httpclient = new CachingHttpClient(realClient, cacheConfig); // Create http context object HttpContext localContext = new BasicHttpContext(); // Check for cached data against URL if (Cache.getInstance().get(url) == null) { // Execute HTTP Get Request HttpGet httpget = new HttpGet(url); // Get http response HttpResponse response = httpclient.execute(httpget, localContext); for (Header h : response.getAllHeaders()) { headers.put(h.getName(), h.getValue()); } // Create http entity object HttpEntity entity = response.getEntity(); // Create and convert stream into string InputStream inStream = entity.getContent(); responseString = convertStreamToString(inStream); // Cache url data Cache.getInstance().put(url, responseString); } else { // Returned cached data responseString = Cache.getInstance().get(url); } } catch (ClientProtocolException e) { // throw custom server exception in case of Exception e.printStackTrace(); throw new ServerException("ClientProtocolException"); } catch (ConnectTimeoutException e) { // throw custom server exception in case of Exception e.printStackTrace(); throw new ServerException("ConnectTimeoutException"); } catch (IOException e) { // throw custom server exception in case of Exception e.printStackTrace(); throw new ServerException("Request Timeout"); } catch (Exception e) { // throw custom server exception in case of Exception e.printStackTrace(); throw new ServerException("Exception"); } finally { } return responseString; }
From source file:com.ridgelineapps.wallpaper.photosite.FiveHundredPxUtils.java
private FiveHundredPxUtils() { final HttpParams params = new BasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, "UTF-8"); final SchemeRegistry registry = new SchemeRegistry(); try {/*from w w w . jav a 2 s .co m*/ registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); registry.register(new Scheme("https", new CustomSSLSocketFactory(), 443)); } catch (Exception e) { e.printStackTrace(); } final ThreadSafeClientConnManager manager = new ThreadSafeClientConnManager(params, registry); mClient = new DefaultHttpClient(manager, params); }