List of usage examples for org.apache.http.impl.conn ProxySelectorRoutePlanner ProxySelectorRoutePlanner
public ProxySelectorRoutePlanner(final SchemeRegistry schreg, final ProxySelector prosel)
From source file:io.github.tavernaextras.biocatalogue.integration.config.BioCataloguePluginConfigurationPanel.java
/** * Saves recent changes to the configuration parameter map. * Some input validation is performed as well. *///from w w w . j ava2 s.co m private void applyChanges() { // --- BioCatalogue BASE URL --- String candidateBaseURL = tfBioCatalogueAPIBaseURL.getText(); if (candidateBaseURL.length() == 0) { JOptionPane.showMessageDialog(this, "Service Catalogue base URL must not be blank", "Service Catalogue Configuration", JOptionPane.WARNING_MESSAGE); tfBioCatalogueAPIBaseURL.requestFocusInWindow(); return; } else { try { new URL(candidateBaseURL); } catch (MalformedURLException e) { JOptionPane.showMessageDialog(this, "Currently set Service Catalogue instance URL is not valid\n." + "Please check the URL and try again.", "Service Catalogue Configuration", JOptionPane.WARNING_MESSAGE); tfBioCatalogueAPIBaseURL.selectAll(); tfBioCatalogueAPIBaseURL.requestFocusInWindow(); return; } // check if the base URL has changed from the last saved state if (!candidateBaseURL.equals( configuration.getProperty(BioCataloguePluginConfiguration.SERVICE_CATALOGUE_BASE_URL))) { // Perform various checks on the new URL // Do a GET with "Accept" header set to "application/xml" // We are expecting a 200 OK and an XML doc in return that // contains the BioCataogue version number element. DefaultHttpClient httpClient = new DefaultHttpClient(); // Set the proxy settings, if any if (System.getProperty(PROXY_HOST) != null && !System.getProperty(PROXY_HOST).equals("")) { // Instruct HttpClient to use the standard // JRE proxy selector to obtain proxy information ProxySelectorRoutePlanner routePlanner = new ProxySelectorRoutePlanner( httpClient.getConnectionManager().getSchemeRegistry(), ProxySelector.getDefault()); httpClient.setRoutePlanner(routePlanner); // Do we need to authenticate the user to the proxy? if (System.getProperty(PROXY_USERNAME) != null && !System.getProperty(PROXY_USERNAME).equals("")) { // Add the proxy username and password to the list of credentials httpClient.getCredentialsProvider().setCredentials( new AuthScope(System.getProperty(PROXY_HOST), Integer.parseInt(System.getProperty(PROXY_PORT))), new UsernamePasswordCredentials(System.getProperty(PROXY_USERNAME), System.getProperty(PROXY_PASSWORD))); } } HttpGet httpGet = new HttpGet(candidateBaseURL); httpGet.setHeader("Accept", APPLICATION_XML_MIME_TYPE); // Execute the request HttpContext localContext = new BasicHttpContext(); HttpResponse httpResponse; try { httpResponse = httpClient.execute(httpGet, localContext); } catch (Exception ex1) { logger.error( "Service Catalogue preferences configuration: Failed to do " + httpGet.getRequestLine(), ex1); // Warn the user JOptionPane.showMessageDialog(this, "Failed to connect to the URL of the Service Catalogue instance.\n" + "Please check the URL and try again.", "Service Catalogue Configuration", JOptionPane.INFORMATION_MESSAGE); // Release resource httpClient.getConnectionManager().shutdown(); tfBioCatalogueAPIBaseURL.requestFocusInWindow(); return; } if (httpResponse.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_OK) { // HTTP/1.1 200 OK HttpEntity httpEntity = httpResponse.getEntity(); String contentType = httpEntity.getContentType().getValue().toLowerCase().trim(); logger.info( "Service Catalogue preferences configuration: Got 200 OK when testing the Service Catalogue instance by doing " + httpResponse.getStatusLine() + ". Content type of response " + contentType); if (contentType.startsWith(APPLICATION_XML_MIME_TYPE)) { String value = null; Document doc = null; try { value = readResponseBodyAsString(httpEntity).trim(); // Try to read this string into an XML document SAXBuilder builder = new SAXBuilder(); byte[] bytes = value.getBytes("UTF-8"); doc = builder.build(new ByteArrayInputStream(bytes)); } catch (Exception ex2) { logger.error( "Service Catalogue preferences configuration: Failed to build an XML document from the response.", ex2); // Warn the user JOptionPane.showMessageDialog(this, "Failed to get the expected response body when testing the Service Catalogue instance.\n" + "The URL is probably wrong. Please check it and try again.", "Service Catalogue Configuration", JOptionPane.INFORMATION_MESSAGE); tfBioCatalogueAPIBaseURL.requestFocusInWindow(); return; } finally { // Release resource httpClient.getConnectionManager().shutdown(); } // Get the version element from the XML document Attribute apiVersionAttribute = doc.getRootElement().getAttribute(API_VERSION); if (apiVersionAttribute != null) { String apiVersion = apiVersionAttribute.getValue(); String versions[] = apiVersion.split("[.]"); String majorVersion = versions[0]; String minorVersion = versions[1]; try { //String patchVersion = versions[2]; // we are not comparing the patch versions String supportedMajorVersion = MIN_SUPPORTED_BIOCATALOGUE_API_VERSION[0]; String supportedMinorVersion = MIN_SUPPORTED_BIOCATALOGUE_API_VERSION[1]; Integer iSupportedMajorVersion = Integer.parseInt(supportedMajorVersion); Integer iMajorVersion = Integer.parseInt(majorVersion); Integer iSupportedMinorVersion = Integer.parseInt(supportedMinorVersion); Integer iMinorVersion = Integer.parseInt(minorVersion); if (!(iSupportedMajorVersion == iMajorVersion && iSupportedMinorVersion <= iMinorVersion)) { // Warn the user JOptionPane.showMessageDialog(this, "The version of the Service Catalogue instance you are trying to connect to is not supported.\n" + "Please change the URL and try again.", "Service Catalogue Configuration", JOptionPane.INFORMATION_MESSAGE); tfBioCatalogueAPIBaseURL.requestFocusInWindow(); return; } } catch (Exception e) { logger.error(e); } } // if null - we'll try to do our best to connect to BioCatalogue anyway } else { logger.error( "Service Catalogue preferences configuration: Failed to get the expected response content type when testing the Service Catalogue instance. " + httpGet.getRequestLine() + " returned content type '" + contentType + "'; expected response content type is 'application/xml'."); // Warn the user JOptionPane.showMessageDialog(this, "Failed to get the expected response content type when testing the Service Catalogue instance.\n" + "The URL is probably wrong. Please check it and try again.", "Service Catalogue Plugin", JOptionPane.INFORMATION_MESSAGE); tfBioCatalogueAPIBaseURL.requestFocusInWindow(); return; } } else { logger.error( "Service Catalogue preferences configuration: Failed to get the expected response status code when testing the Service Catalogue instance. " + httpGet.getRequestLine() + " returned the status code " + httpResponse.getStatusLine().getStatusCode() + "; expected status code is 200 OK."); // Warn the user JOptionPane.showMessageDialog(this, "Failed to get the expected response status code when testing the Service Catalogue instance.\n" + "The URL is probably wrong. Please check it and try again.", "Service Catalogue Configuration", JOptionPane.INFORMATION_MESSAGE); tfBioCatalogueAPIBaseURL.requestFocusInWindow(); return; } // Warn the user of the changes in the BioCatalogue base URL JOptionPane.showMessageDialog(this, "You have updated the Service Catalogue base URL.\n" + "This does not take effect until you restart Taverna.", "Service catalogue Configuration", JOptionPane.INFORMATION_MESSAGE); } // the new base URL seems to be valid - can save it into config // settings configuration.setProperty(BioCataloguePluginConfiguration.SERVICE_CATALOGUE_BASE_URL, candidateBaseURL); /* // also update the base URL in the BioCatalogueClient BioCatalogueClient.getInstance() .setBaseURL(candidateBaseURL);*/ } }
From source file:net.oddsoftware.android.feedscribe.data.Downloader.java
private HttpClient createHttpClient() { // use apache http client lib to set parameters from feedStatus DefaultHttpClient client = new DefaultHttpClient(); // set up proxy handler ProxySelectorRoutePlanner routePlanner = new ProxySelectorRoutePlanner( client.getConnectionManager().getSchemeRegistry(), ProxySelector.getDefault()); client.setRoutePlanner(routePlanner); return client; }
From source file:org.apache.abdera2.common.protocol.BasicClient.java
/** * Configure the client to use the proxy configured for the JVM * @return/* www. ja v a 2s . c om*/ */ public <T extends Client> T setStandardProxy() { ProxySelectorRoutePlanner routePlanner = new ProxySelectorRoutePlanner( client.getConnectionManager().getSchemeRegistry(), ProxySelector.getDefault()); getDefaultHttpClient().setRoutePlanner(routePlanner); return (T) this; }
From source file:com.android.tools.idea.sdk.remote.internal.UrlOpener.java
@NonNull private static Pair<InputStream, HttpResponse> openWithHttpClient(@NonNull String url, @NonNull ITaskMonitor monitor, Header[] inHeaders) throws IOException, CanceledByUserException { UserCredentials result = null;/*from w w w . ja v a2 s .c o m*/ String realm = null; HttpParams params = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(params, sConnectionTimeoutMs); HttpConnectionParams.setSoTimeout(params, sSocketTimeoutMs); // use the simple one final DefaultHttpClient httpClient = new DefaultHttpClient(params); // create local execution context HttpContext localContext = new BasicHttpContext(); final HttpGet httpGet = new HttpGet(url); if (inHeaders != null) { for (Header header : inHeaders) { httpGet.addHeader(header); } } // retrieve local java configured network in case there is the need to // authenticate a proxy ProxySelectorRoutePlanner routePlanner = new ProxySelectorRoutePlanner( httpClient.getConnectionManager().getSchemeRegistry(), ProxySelector.getDefault()); httpClient.setRoutePlanner(routePlanner); // Set preference order for authentication options. // In particular, we don't add AuthPolicy.SPNEGO, which is given preference over NTLM in // servers that support both, as it is more secure. However, we don't seem to handle it // very well, so we leave it off the list. // See http://hc.apache.org/httpcomponents-client-ga/tutorial/html/authentication.html for // more info. List<String> authpref = new ArrayList<String>(); authpref.add(AuthPolicy.BASIC); authpref.add(AuthPolicy.DIGEST); authpref.add(AuthPolicy.NTLM); httpClient.getParams().setParameter(AuthPNames.PROXY_AUTH_PREF, authpref); httpClient.getParams().setParameter(AuthPNames.TARGET_AUTH_PREF, authpref); if (DEBUG) { try { URI uri = new URI(url); ProxySelector sel = routePlanner.getProxySelector(); if (sel != null && uri.getScheme().startsWith("httP")) { //$NON-NLS-1$ List<Proxy> list = sel.select(uri); System.out.printf("SdkLib.UrlOpener:\n Connect to: %s\n Proxy List: %s\n", //$NON-NLS-1$ url, list == null ? "(null)" : Arrays.toString(list.toArray()));//$NON-NLS-1$ } } catch (Exception e) { System.out.printf("SdkLib.UrlOpener: Failed to get proxy info for %s: %s\n", //$NON-NLS-1$ url, e.toString()); } } boolean trying = true; // loop while the response is being fetched while (trying) { // connect and get status code HttpResponse response = httpClient.execute(httpGet, localContext); int statusCode = response.getStatusLine().getStatusCode(); if (DEBUG) { System.out.printf(" Status: %d\n", statusCode); //$NON-NLS-1$ } // check whether any authentication is required AuthState authenticationState = null; if (statusCode == HttpStatus.SC_UNAUTHORIZED) { // Target host authentication required authenticationState = (AuthState) localContext.getAttribute(ClientContext.TARGET_AUTH_STATE); } if (statusCode == HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED) { // Proxy authentication required authenticationState = (AuthState) localContext.getAttribute(ClientContext.PROXY_AUTH_STATE); } if (statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_NOT_MODIFIED) { // in case the status is OK and there is a realm and result, // cache it if (realm != null && result != null) { sRealmCache.put(realm, result); } } // there is the need for authentication if (authenticationState != null) { // get scope and realm AuthScope authScope = authenticationState.getAuthScope(); // If the current realm is different from the last one it means // a pass was performed successfully to the last URL, therefore // cache the last realm if (realm != null && !realm.equals(authScope.getRealm())) { sRealmCache.put(realm, result); } realm = authScope.getRealm(); // in case there is cache for this Realm, use it to authenticate if (sRealmCache.containsKey(realm)) { result = sRealmCache.get(realm); } else { // since there is no cache, request for login and password result = monitor.displayLoginCredentialsPrompt("Site Authentication", "Please login to the following domain: " + realm + "\n\nServer requiring authentication:\n" + authScope.getHost()); if (result == null) { throw new CanceledByUserException("User canceled login dialog."); } } // retrieve authentication data String user = result.getUserName(); String password = result.getPassword(); String workstation = result.getWorkstation(); String domain = result.getDomain(); // proceed in case there is indeed a user if (user != null && user.length() > 0) { Credentials credentials = new NTCredentials(user, password, workstation, domain); httpClient.getCredentialsProvider().setCredentials(authScope, credentials); trying = true; } else { trying = false; } } else { trying = false; } HttpEntity entity = response.getEntity(); if (entity != null) { if (trying) { // in case another pass to the Http Client will be performed, close the entity. entity.getContent().close(); } else { // since no pass to the Http Client is needed, retrieve the // entity's content. // Note: don't use something like a BufferedHttpEntity since it would consume // all content and store it in memory, resulting in an OutOfMemory exception // on a large download. InputStream is = new FilterInputStream(entity.getContent()) { @Override public void close() throws IOException { // Since Http Client is no longer needed, close it. // Bug #21167: we need to tell http client to shutdown // first, otherwise the super.close() would continue // downloading and not return till complete. httpClient.getConnectionManager().shutdown(); super.close(); } }; HttpResponse outResponse = new BasicHttpResponse(response.getStatusLine()); outResponse.setHeaders(response.getAllHeaders()); outResponse.setLocale(response.getLocale()); return Pair.of(is, outResponse); } } else if (statusCode == HttpStatus.SC_NOT_MODIFIED) { // It's ok to not have an entity (e.g. nothing to download) for a 304 HttpResponse outResponse = new BasicHttpResponse(response.getStatusLine()); outResponse.setHeaders(response.getAllHeaders()); outResponse.setLocale(response.getLocale()); return Pair.of(null, outResponse); } } // We get here if we did not succeed. Callers do not expect a null result. httpClient.getConnectionManager().shutdown(); throw new FileNotFoundException(url); }
From source file:org.apache.taverna.activities.rest.HTTPRequestHandler.java
/** * TODO - REDIRECTION output:: if there was no redirection, should just show * the actual initial URL?// w w w . j a va 2s .co m * * @param httpRequest * @param acceptHeaderValue */ private static HTTPRequestResponse performHTTPRequest(ClientConnectionManager connectionManager, HttpRequestBase httpRequest, RESTActivityConfigurationBean configBean, Map<String, String> urlParameters, CredentialsProvider credentialsProvider) { // headers are set identically for all HTTP methods, therefore can do // centrally - here // If the user wants to set MIME type for the 'Accepts' header String acceptsHeaderValue = configBean.getAcceptsHeaderValue(); if ((acceptsHeaderValue != null) && !acceptsHeaderValue.isEmpty()) { httpRequest.setHeader(ACCEPT_HEADER_NAME, URISignatureHandler.generateCompleteURI(acceptsHeaderValue, urlParameters, configBean.getEscapeParameters())); } // See if user wanted to set any other HTTP headers ArrayList<ArrayList<String>> otherHTTPHeaders = configBean.getOtherHTTPHeaders(); if (!otherHTTPHeaders.isEmpty()) for (ArrayList<String> httpHeaderNameValuePair : otherHTTPHeaders) if (httpHeaderNameValuePair.get(0) != null && !httpHeaderNameValuePair.get(0).isEmpty()) { String headerParameterizedValue = httpHeaderNameValuePair.get(1); String headerValue = URISignatureHandler.generateCompleteURI(headerParameterizedValue, urlParameters, configBean.getEscapeParameters()); httpRequest.setHeader(httpHeaderNameValuePair.get(0), headerValue); } try { HTTPRequestResponse requestResponse = new HTTPRequestResponse(); DefaultHttpClient httpClient = new DefaultHttpClient(connectionManager, null); ((DefaultHttpClient) httpClient).setCredentialsProvider(credentialsProvider); HttpContext localContext = new BasicHttpContext(); // Set the proxy settings, if any if (System.getProperty(PROXY_HOST) != null && !System.getProperty(PROXY_HOST).isEmpty()) { // Instruct HttpClient to use the standard // JRE proxy selector to obtain proxy information ProxySelectorRoutePlanner routePlanner = new ProxySelectorRoutePlanner( httpClient.getConnectionManager().getSchemeRegistry(), ProxySelector.getDefault()); httpClient.setRoutePlanner(routePlanner); // Do we need to authenticate the user to the proxy? if (System.getProperty(PROXY_USERNAME) != null && !System.getProperty(PROXY_USERNAME).isEmpty()) // Add the proxy username and password to the list of // credentials httpClient.getCredentialsProvider().setCredentials( new AuthScope(System.getProperty(PROXY_HOST), Integer.parseInt(System.getProperty(PROXY_PORT))), new UsernamePasswordCredentials(System.getProperty(PROXY_USERNAME), System.getProperty(PROXY_PASSWORD))); } // execute the request HttpResponse response = httpClient.execute(httpRequest, localContext); // record response code requestResponse.setStatusCode(response.getStatusLine().getStatusCode()); requestResponse.setReasonPhrase(response.getStatusLine().getReasonPhrase()); // record header values for Content-Type of the response requestResponse.setResponseContentTypes(response.getHeaders(CONTENT_TYPE_HEADER_NAME)); // track where did the final redirect go to (if there was any) HttpHost targetHost = (HttpHost) localContext.getAttribute(ExecutionContext.HTTP_TARGET_HOST); HttpUriRequest targetRequest = (HttpUriRequest) localContext .getAttribute(ExecutionContext.HTTP_REQUEST); requestResponse.setRedirectionURL("" + targetHost + targetRequest.getURI()); requestResponse.setRedirectionHTTPMethod(targetRequest.getMethod()); requestResponse.setHeaders(response.getAllHeaders()); /* read and store response body (check there is some content - negative length of content means unknown length; zero definitely means no content...)*/ // TODO - make sure that this test is sufficient to determine if // there is no response entity if (response.getEntity() != null && response.getEntity().getContentLength() != 0) requestResponse.setResponseBody(readResponseBody(response.getEntity())); // release resources (e.g. connection pool, etc) httpClient.getConnectionManager().shutdown(); return requestResponse; } catch (Exception ex) { return new HTTPRequestResponse(ex); } }
From source file:gov.nih.nci.nbia.StandaloneDMV3.java
private List<String> connectAndReadFromURL(URL url, List<String> seriesList, String userId, String passWd) { List<String> data = null; DefaultHttpClient httpClient = null; TrustStrategy easyStrategy = new TrustStrategy() { @Override//from w w w . j a va2s . co m public boolean isTrusted(X509Certificate[] certificate, String authType) throws CertificateException { return true; } }; try { // SSLContext sslContext = SSLContext.getInstance("SSL"); // set up a TrustManager that trusts everything // sslContext.init(null, new TrustManager[] { new // EasyX509TrustManager(null)}, null); SSLSocketFactory sslsf = new SSLSocketFactory(easyStrategy, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); Scheme httpsScheme = new Scheme("https", 443, sslsf); SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(httpsScheme); schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory())); ClientConnectionManager ccm = new ThreadSafeClientConnManager(schemeRegistry); HttpParams httpParams = new BasicHttpParams(); // HttpConnectionParams.setConnectionTimeout(httpParams, 50000); // HttpConnectionParams.setSoTimeout(httpParams, new // Integer(12000)); HttpConnectionParams.setConnectionTimeout(httpParams, 500000); HttpConnectionParams.setSoTimeout(httpParams, new Integer(120000)); httpClient = new DefaultHttpClient(ccm, httpParams); httpClient.setRoutePlanner(new ProxySelectorRoutePlanner(schemeRegistry, ProxySelector.getDefault())); // // Additions by lrt for tcia - // // attempt to reduce errors going through a Coyote Point // Equalizer load balance switch // httpClient.getParams().setParameter("http.socket.timeout", new // Integer(12000)); httpClient.getParams().setParameter("http.socket.timeout", new Integer(120000)); httpClient.getParams().setParameter("http.socket.receivebuffer", new Integer(16384)); httpClient.getParams().setParameter("http.tcp.nodelay", true); httpClient.getParams().setParameter("http.connection.stalecheck", false); // // end lrt additions HttpPost httpPostMethod = new HttpPost(url.toString()); List<BasicNameValuePair> postParams = new ArrayList<BasicNameValuePair>(); if (userId != null && passWd != null) { postParams.add(new BasicNameValuePair("userId", userId)); httpPostMethod.addHeader("password", passWd); } postParams.add(new BasicNameValuePair("numberOfSeries", Integer.toString(seriesList.size()))); int i = 0; for (String s : seriesList) { postParams.add(new BasicNameValuePair("series" + Integer.toString(++i), s)); } UrlEncodedFormEntity query = new UrlEncodedFormEntity(postParams); httpPostMethod.setEntity(query); HttpResponse response = httpClient.execute(httpPostMethod); int responseCode = response.getStatusLine().getStatusCode(); if (responseCode != HttpURLConnection.HTTP_OK) { returnStatus = responseCode; return null; } else { InputStream inputStream = response.getEntity().getContent(); data = IOUtils.readLines(inputStream); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (KeyManagementException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NoSuchAlgorithmException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (KeyStoreException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (UnrecoverableKeyException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { if (httpClient != null) { httpClient.getConnectionManager().shutdown(); } } return data; }
From source file:com.naryx.tagfusion.cfm.http.cfHttpConnection.java
private void setDefaultProxy() { HttpHost currentProxy = (HttpHost) client.getParams().getParameter(ConnRoutePNames.DEFAULT_PROXY); if (currentProxy == null) { ProxySelectorRoutePlanner routePlanner = new ProxySelectorRoutePlanner( client.getConnectionManager().getSchemeRegistry(), ProxySelector.getDefault()); client.setRoutePlanner(routePlanner); }/*from w ww .ja va 2 s .co m*/ }
From source file:net.oddsoftware.android.feedscribe.data.FeedManager.java
void downloadImage(String address, boolean persistant) { if (mDB.hasImage(address)) { mDB.updateImageTime(address, new Date().getTime()); return;/*w w w. java 2s . c om*/ } try { // use apache http client lib to set parameters from feedStatus DefaultHttpClient client = new DefaultHttpClient(); // set up proxy handler ProxySelectorRoutePlanner routePlanner = new ProxySelectorRoutePlanner( client.getConnectionManager().getSchemeRegistry(), ProxySelector.getDefault()); client.setRoutePlanner(routePlanner); HttpGet request = new HttpGet(address); request.setHeader("User-Agent", USER_AGENT); HttpResponse response = client.execute(request); StatusLine status = response.getStatusLine(); HttpEntity entity = response.getEntity(); if (entity != null && status.getStatusCode() == 200) { InputStream inputStream = entity.getContent(); // TODO - parse content-length here ByteArrayOutputStream data = new ByteArrayOutputStream(); byte bytes[] = new byte[512]; int count; while ((count = inputStream.read(bytes)) > 0) { data.write(bytes, 0, count); } if (data.size() > 0) { mDB.insertImage(address, new Date().getTime(), persistant, data.toByteArray()); } } } catch (IOException exc) { if (mLog.e()) mLog.e("error downloading image" + address, exc); } }
From source file:gov.nih.nci.nbia.StandaloneDMDispatcher.java
private static List<String> connectAndReadFromURL(URL url) { List<String> data = null; DefaultHttpClient httpClient = null; TrustStrategy easyStrategy = new TrustStrategy() { @Override//from w ww.j a v a2 s .co m public boolean isTrusted(X509Certificate[] certificate, String authType) throws CertificateException { return true; } }; try { SSLSocketFactory sslsf = new SSLSocketFactory(easyStrategy, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); Scheme httpsScheme = new Scheme("https", 443, sslsf); SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(httpsScheme); schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory())); ClientConnectionManager ccm = new ThreadSafeClientConnManager(schemeRegistry); HttpParams httpParams = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpParams, 50000); HttpConnectionParams.setSoTimeout(httpParams, new Integer(12000)); httpClient = new DefaultHttpClient(ccm, httpParams); httpClient.setRoutePlanner(new ProxySelectorRoutePlanner(schemeRegistry, ProxySelector.getDefault())); // // Additions by lrt for tcia - // // attempt to reduce errors going through a Coyote Point // Equalizer load balance switch httpClient.getParams().setParameter("http.socket.timeout", new Integer(12000)); httpClient.getParams().setParameter("http.socket.receivebuffer", new Integer(16384)); httpClient.getParams().setParameter("http.tcp.nodelay", true); httpClient.getParams().setParameter("http.connection.stalecheck", false); // // end lrt additions HttpPost httpPostMethod = new HttpPost(url.toString()); List<BasicNameValuePair> postParams = new ArrayList<BasicNameValuePair>(); postParams.add(new BasicNameValuePair(osParam, os)); UrlEncodedFormEntity query = new UrlEncodedFormEntity(postParams); httpPostMethod.setEntity(query); HttpResponse response = httpClient.execute(httpPostMethod); int responseCode = response.getStatusLine().getStatusCode(); if (responseCode == HttpStatus.SC_OK) { InputStream inputStream = response.getEntity().getContent(); data = IOUtils.readLines(inputStream); } else { JOptionPane.showMessageDialog(null, "Incorrect response from server: " + responseCode); } } catch (java.net.ConnectException e) { String note = "Connection error 1 while connecting to " + url.toString() + ":\n" + getProxyInfo(); //+ checkListeningPort("127.0.0.1", 8888); printStackTraceToDialog(note, e); //JOptionPane.showMessageDialog(null, "Connection error 1: " + e.getMessage()); e.printStackTrace(); } catch (MalformedURLException e) { String note = "Connection error 2 while connecting to " + url.toString() + ":\n"; printStackTraceToDialog(note, e); //JOptionPane.showMessageDialog(null, "Connection error 2: " + e.getMessage()); e.printStackTrace(); } catch (IOException e) { String note = "Connection error 3 while connecting to " + url.toString() + ":\n"; printStackTraceToDialog(note, e); //JOptionPane.showMessageDialog(null, "Connection error 3: " + e.getMessage()); e.printStackTrace(); } catch (KeyManagementException e) { String note = "Connection error 4 while connecting to " + url.toString() + ":\n"; printStackTraceToDialog(note, e); //JOptionPane.showMessageDialog(null, "Connection error 4: " + e.getMessage()); e.printStackTrace(); } catch (NoSuchAlgorithmException e) { String note = "Connection error 5 while connecting to " + url.toString() + ":\n"; printStackTraceToDialog(note, e); //JOptionPane.showMessageDialog(null, "Connection error 5: " + e.getMessage()); e.printStackTrace(); } catch (KeyStoreException e) { String note = "Connection error 6 while connecting to " + url.toString() + ":\n"; printStackTraceToDialog(note, e); //JOptionPane.showMessageDialog(null, "Connection error 6: " + e.getMessage()); e.printStackTrace(); } catch (UnrecoverableKeyException e) { String note = "Connection error 7 while connecting to " + url.toString() + ":\n"; printStackTraceToDialog(note, e); //JOptionPane.showMessageDialog(null, "Connection error 7: " + e.getMessage()); e.printStackTrace(); } finally { if (httpClient != null) { httpClient.getConnectionManager().shutdown(); } } return data; }
From source file:net.oddsoftware.android.feedscribe.data.FeedManager.java
void downloadFeedHttp(Feed feed, FeedStatus feedStatus, ArrayList<FeedItem> feedItems, ArrayList<Enclosure> enclosures) { try {//ww w .ja v a2s . c om // use apache http client lib to set parameters from feedStatus DefaultHttpClient client = new DefaultHttpClient(); // set up proxy handler ProxySelectorRoutePlanner routePlanner = new ProxySelectorRoutePlanner( client.getConnectionManager().getSchemeRegistry(), ProxySelector.getDefault()); client.setRoutePlanner(routePlanner); HttpGet request = new HttpGet(feed.mURL); HttpContext httpContext = new BasicHttpContext(); request.setHeader("User-Agent", USER_AGENT); // send etag if we have it if (feedStatus.mETag.length() > 0) { request.setHeader("If-None-Match", feedStatus.mETag); } // send If-Modified-Since if we have it if (feedStatus.mLastModified.getTime() > 0) { SimpleDateFormat dateFormat = new SimpleDateFormat("EEE', 'dd' 'MMM' 'yyyy' 'HH:mm:ss' GMT'", Locale.US); dateFormat.setTimeZone(TimeZone.getTimeZone("GMT")); String formattedTime = dateFormat.format(feedStatus.mLastModified); // If-Modified-Since: Sat, 29 Oct 1994 19:43:31 GMT request.setHeader("If-Modified-Since", formattedTime); } request.setHeader("Accept-Encoding", "gzip,deflate"); HttpResponse response = client.execute(request, httpContext); if (mLog.d()) mLog.d("http request: " + feed.mURL); if (mLog.d()) mLog.d("http response code: " + response.getStatusLine()); InputStream inputStream = null; StatusLine status = response.getStatusLine(); HttpEntity entity = response.getEntity(); if (entity != null) { inputStream = entity.getContent(); } try { if (entity != null && status.getStatusCode() == 200) { Header encodingHeader = entity.getContentEncoding(); if (encodingHeader != null) { if (encodingHeader.getValue().equalsIgnoreCase("gzip")) { inputStream = new GZIPInputStream(inputStream); } else if (encodingHeader.getValue().equalsIgnoreCase("deflate")) { inputStream = new InflaterInputStream(inputStream); } } // remove caching attributes to be replaced with new ones feedStatus.mETag = ""; feedStatus.mLastModified.setTime(0); feedStatus.mTTL = 0; boolean success = parseFeed(inputStream, feed, feedStatus, feedItems, enclosures); if (success) { // if the parse was ok, update these attributes // ETag: "6050003-78e5-4981d775e87c0" Header etagHeader = response.getFirstHeader("ETag"); if (etagHeader != null) { if (etagHeader.getValue().length() < MAX_ETAG_LENGTH) { feedStatus.mETag = etagHeader.getValue(); } else { mLog.e("etag length was too big: " + etagHeader.getValue().length()); } } // Last-Modified: Fri, 24 Dec 2010 00:57:11 GMT Header lastModifiedHeader = response.getFirstHeader("Last-Modified"); if (lastModifiedHeader != null) { try { feedStatus.mLastModified = parseRFC822Date(lastModifiedHeader.getValue()); } catch (ParseException exc) { mLog.e("unable to parse date", exc); } } HttpUriRequest currentReq = (HttpUriRequest) httpContext .getAttribute(ExecutionContext.HTTP_REQUEST); HttpHost currentHost = (HttpHost) httpContext .getAttribute(ExecutionContext.HTTP_TARGET_HOST); String currentUrl = currentHost.toURI() + currentReq.getURI(); mLog.w("loaded redirect from " + request.getURI().toString() + " to " + currentUrl); feedStatus.mLastURL = currentUrl; } } else { if (status.getStatusCode() == 304) { mLog.d("received 304 not modified"); } } } finally { if (inputStream != null) { inputStream.close(); } } } catch (IOException exc) { mLog.e("error downloading feed " + feed.mURL, exc); } }