List of usage examples for java.net ProxySelector getDefault
public static ProxySelector getDefault()
From source file:org.opennms.core.web.HttpClientWrapper.java
public CloseableHttpClient getClient() { if (m_httpClient == null) { final HttpClientBuilder httpClientBuilder = HttpClientBuilder.create(); final RequestConfig.Builder requestConfigBuilder = RequestConfig.custom(); if (!m_reuseConnections) { httpClientBuilder.setConnectionReuseStrategy(new NoConnectionReuseStrategy()); }//from www . j a v a2s . co m if (m_usePreemptiveAuth) { enablePreemptiveAuth(httpClientBuilder); } if (m_useSystemProxySettings) { httpClientBuilder.setRoutePlanner(new SystemDefaultRoutePlanner(ProxySelector.getDefault())); } if (!isEmpty(m_cookieSpec)) { requestConfigBuilder.setCookieSpec(m_cookieSpec); } if (m_cookieStore != null) { httpClientBuilder.setDefaultCookieStore(m_cookieStore); } if (m_username != null) { setCredentials(httpClientBuilder, m_username, m_password); } if (m_socketTimeout != null) { requestConfigBuilder.setSocketTimeout(m_socketTimeout); } if (m_connectionTimeout != null) { requestConfigBuilder.setConnectTimeout(m_connectionTimeout); } if (m_retries != null) { httpClientBuilder.setRetryHandler(new HttpRequestRetryOnExceptionHandler(m_retries, false)); } if (m_sslContext.size() != 0) { configureSSLContext(httpClientBuilder); } for (final HttpRequestInterceptor interceptor : m_requestInterceptors) { httpClientBuilder.addInterceptorLast(interceptor); } for (final HttpResponseInterceptor interceptor : m_responseInterceptors) { httpClientBuilder.addInterceptorLast(interceptor); } if (m_useLaxRedirect) { httpClientBuilder.setRedirectStrategy(new LaxRedirectStrategy()); } httpClientBuilder.setDefaultRequestConfig(requestConfigBuilder.build()); m_httpClient = httpClientBuilder.build(); } return m_httpClient; }
From source file:eu.peppol.outbound.transmission.As2MessageSender.java
CloseableHttpClient createCloseableHttpClient() { // "SSLv3" is disabled by default : http://www.apache.org/dist/httpcomponents/httpclient/RELEASE_NOTES-4.3.x.txt SystemDefaultRoutePlanner routePlanner = new SystemDefaultRoutePlanner(ProxySelector.getDefault()); CloseableHttpClient httpclient = HttpClients.custom().setRoutePlanner(routePlanner).build(); return httpclient; }
From source file:com.syncleus.maven.plugins.mongodb.StartMongoMojo.java
private void addProxySelector() { // Add authenticator with proxyUser and proxyPassword if (proxyUser != null && proxyPassword != null) { Authenticator.setDefault(new Authenticator() { @Override/*w ww . jav a 2 s .co m*/ public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(proxyUser, proxyPassword.toCharArray()); } }); } final ProxySelector defaultProxySelector = ProxySelector.getDefault(); ProxySelector.setDefault(new ProxySelector() { @Override public List<Proxy> select(final URI uri) { if (uri.getHost().equals("fastdl.mongodb.org")) { return singletonList(new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort))); } else { return defaultProxySelector.select(uri); } } @Override public void connectFailed(final URI uri, final SocketAddress sa, final IOException ioe) { } }); }
From source file:jp.ne.sakura.kkkon.java.net.inetaddress.testapp.android.NetworkConnectionCheckerTestApp.java
/** Called when the activity is first created. */ @Override//from ww w . jav a 2 s .c o m public void onCreate(Bundle savedInstanceState) { final Context context = this.getApplicationContext(); { NetworkConnectionChecker.initialize(); } super.onCreate(savedInstanceState); /* Create a TextView and set its content. * the text is retrieved by calling a native * function. */ LinearLayout layout = new LinearLayout(this); layout.setOrientation(LinearLayout.VERTICAL); TextView tv = new TextView(this); tv.setText("reachable="); layout.addView(tv); this.textView = tv; Button btn1 = new Button(this); btn1.setText("invoke Exception"); btn1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { final int count = 2; int[] array = new int[count]; int value = array[count]; // invoke IndexOutOfBOundsException } }); layout.addView(btn1); { Button btn = new Button(this); btn.setText("disp isReachable"); btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { final boolean isReachable = NetworkConnectionChecker.isReachable(); Toast toast = Toast.makeText(context, "IsReachable=" + isReachable, Toast.LENGTH_LONG); toast.show(); } }); layout.addView(btn); } { Button btn = new Button(this); btn.setText("upload http AsyncTask"); btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { AsyncTask<String, Void, Boolean> asyncTask = new AsyncTask<String, Void, Boolean>() { @Override protected Boolean doInBackground(String... paramss) { Boolean result = true; Log.d(TAG, "upload AsyncTask tid=" + android.os.Process.myTid()); try { //$(BRAND)/$(PRODUCT)/$(DEVICE)/$(BOARD):$(VERSION.RELEASE)/$(ID)/$(VERSION.INCREMENTAL):$(TYPE)/$(TAGS) Log.d(TAG, "fng=" + Build.FINGERPRINT); final List<NameValuePair> list = new ArrayList<NameValuePair>(16); list.add(new BasicNameValuePair("fng", Build.FINGERPRINT)); HttpPost httpPost = new HttpPost(paramss[0]); //httpPost.getParams().setParameter( CoreConnectionPNames.SO_TIMEOUT, new Integer(5*1000) ); httpPost.setEntity(new UrlEncodedFormEntity(list, HTTP.UTF_8)); DefaultHttpClient httpClient = new DefaultHttpClient(); Log.d(TAG, "socket.timeout=" + httpClient.getParams() .getIntParameter(CoreConnectionPNames.SO_TIMEOUT, -1)); Log.d(TAG, "connection.timeout=" + httpClient.getParams() .getIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, -1)); httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, new Integer(5 * 1000)); httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, new Integer(5 * 1000)); Log.d(TAG, "socket.timeout=" + httpClient.getParams() .getIntParameter(CoreConnectionPNames.SO_TIMEOUT, -1)); Log.d(TAG, "connection.timeout=" + httpClient.getParams() .getIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, -1)); // <uses-permission android:name="android.permission.INTERNET"/> // got android.os.NetworkOnMainThreadException, run at UI Main Thread HttpResponse response = httpClient.execute(httpPost); Log.d(TAG, "response=" + response.getStatusLine().getStatusCode()); } catch (Exception e) { Log.d(TAG, "got Exception. msg=" + e.getMessage(), e); result = false; } Log.d(TAG, "upload finish"); return result; } }; asyncTask.execute("http://kkkon.sakura.ne.jp/android/bug"); asyncTask.isCancelled(); } }); layout.addView(btn); } { Button btn = new Button(this); btn.setText("pre DNS query(0.0.0.0)"); btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { isReachable = false; Thread thread = new Thread(new Runnable() { public void run() { try { destHost = InetAddress.getByName("0.0.0.0"); if (null != destHost) { try { if (destHost.isReachable(5 * 1000)) { Log.d(TAG, "destHost=" + destHost.toString() + " reachable"); } else { Log.d(TAG, "destHost=" + destHost.toString() + " not reachable"); } } catch (IOException e) { } } } catch (UnknownHostException e) { } Log.d(TAG, "destHost=" + destHost); } }); thread.start(); try { thread.join(1000); } catch (InterruptedException e) { } } }); layout.addView(btn); } { Button btn = new Button(this); btn.setText("pre DNS query(www.google.com)"); btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { isReachable = false; Thread thread = new Thread(new Runnable() { public void run() { Log.d(TAG, "start"); try { InetAddress dest = InetAddress.getByName("www.google.com"); if (null == dest) { dest = destHost; } if (null != dest) { final String[] uris = new String[] { "http://www.google.com/", "https://www.google.com/" }; for (final String destURI : uris) { URI uri = null; try { uri = new URI(destURI); } catch (URISyntaxException e) { //Log.d( TAG, e.toString() ); } if (null != uri) { URL url = null; try { url = uri.toURL(); } catch (MalformedURLException ex) { Log.d(TAG, "got exception:" + ex.toString(), ex); } URLConnection conn = null; if (null != url) { Log.d(TAG, "openConnection before"); try { conn = url.openConnection(); if (null != conn) { conn.setConnectTimeout(3 * 1000); conn.setReadTimeout(3 * 1000); } } catch (IOException e) { //Log.d( TAG, "got Exception" + e.toString(), e ); } Log.d(TAG, "openConnection after"); if (conn instanceof HttpURLConnection) { HttpURLConnection httpConn = (HttpURLConnection) conn; int responceCode = -1; try { Log.d(TAG, "getResponceCode before"); responceCode = httpConn.getResponseCode(); Log.d(TAG, "getResponceCode after"); } catch (IOException ex) { Log.d(TAG, "got exception:" + ex.toString(), ex); } Log.d(TAG, "responceCode=" + responceCode); if (0 < responceCode) { isReachable = true; destHost = dest; } Log.d(TAG, " HTTP ContentLength=" + httpConn.getContentLength()); httpConn.disconnect(); Log.d(TAG, " HTTP ContentLength=" + httpConn.getContentLength()); } } } // if uri if (isReachable) { //break; } } // for uris } else { } } catch (UnknownHostException e) { Log.d(TAG, "dns error" + e.toString()); destHost = null; } { if (null != destHost) { Log.d(TAG, "destHost=" + destHost); } } Log.d(TAG, "end"); } }); thread.start(); try { thread.join(); { final String addr = (null == destHost) ? ("") : (destHost.toString()); final String reachable = (isReachable) ? ("reachable") : ("not reachable"); Toast toast = Toast.makeText(context, "DNS result=\n" + addr + "\n " + reachable, Toast.LENGTH_LONG); toast.show(); } } catch (InterruptedException e) { } } }); layout.addView(btn); } { Button btn = new Button(this); btn.setText("pre DNS query(kkkon.sakura.ne.jp)"); btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { isReachable = false; Thread thread = new Thread(new Runnable() { public void run() { Log.d(TAG, "start"); try { InetAddress dest = InetAddress.getByName("kkkon.sakura.ne.jp"); if (null == dest) { dest = destHost; } if (null != dest) { try { if (dest.isReachable(5 * 1000)) { Log.d(TAG, "destHost=" + dest.toString() + " reachable"); isReachable = true; } else { Log.d(TAG, "destHost=" + dest.toString() + " not reachable"); } destHost = dest; } catch (IOException e) { } } else { } } catch (UnknownHostException e) { Log.d(TAG, "dns error" + e.toString()); destHost = null; } { if (null != destHost) { Log.d(TAG, "destHost=" + destHost); } } Log.d(TAG, "end"); } }); thread.start(); try { thread.join(); { final String addr = (null == destHost) ? ("") : (destHost.toString()); final String reachable = (isReachable) ? ("reachable") : ("not reachable"); Toast toast = Toast.makeText(context, "DNS result=\n" + addr + "\n " + reachable, Toast.LENGTH_LONG); toast.show(); } } catch (InterruptedException e) { } } }); layout.addView(btn); } { Button btn = new Button(this); btn.setText("pre DNS query(kkkon.sakura.ne.jp) support proxy"); btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { isReachable = false; Thread thread = new Thread(new Runnable() { public void run() { try { String target = null; { ProxySelector proxySelector = ProxySelector.getDefault(); Log.d(TAG, "proxySelector=" + proxySelector); if (null != proxySelector) { URI uri = null; try { uri = new URI("http://www.google.com/"); } catch (URISyntaxException e) { Log.d(TAG, e.toString()); } List<Proxy> proxies = proxySelector.select(uri); if (null != proxies) { for (final Proxy proxy : proxies) { Log.d(TAG, " proxy=" + proxy); if (null != proxy) { if (Proxy.Type.HTTP == proxy.type()) { final SocketAddress sa = proxy.address(); if (sa instanceof InetSocketAddress) { final InetSocketAddress isa = (InetSocketAddress) sa; target = isa.getHostName(); break; } } } } } } } if (null == target) { target = "kkkon.sakura.ne.jp"; } InetAddress dest = InetAddress.getByName(target); if (null == dest) { dest = destHost; } if (null != dest) { try { if (dest.isReachable(5 * 1000)) { Log.d(TAG, "destHost=" + dest.toString() + " reachable"); isReachable = true; } else { Log.d(TAG, "destHost=" + dest.toString() + " not reachable"); { ProxySelector proxySelector = ProxySelector.getDefault(); //Log.d( TAG, "proxySelector=" + proxySelector ); if (null != proxySelector) { URI uri = null; try { uri = new URI("http://www.google.com/"); } catch (URISyntaxException e) { //Log.d( TAG, e.toString() ); } if (null != uri) { List<Proxy> proxies = proxySelector.select(uri); if (null != proxies) { for (final Proxy proxy : proxies) { //Log.d( TAG, " proxy=" + proxy ); if (null != proxy) { if (Proxy.Type.HTTP == proxy.type()) { URL url = uri.toURL(); URLConnection conn = null; if (null != url) { try { conn = url.openConnection(proxy); if (null != conn) { conn.setConnectTimeout( 3 * 1000); conn.setReadTimeout(3 * 1000); } } catch (IOException e) { Log.d(TAG, "got Exception" + e.toString(), e); } if (conn instanceof HttpURLConnection) { HttpURLConnection httpConn = (HttpURLConnection) conn; if (0 < httpConn .getResponseCode()) { isReachable = true; } Log.d(TAG, " HTTP ContentLength=" + httpConn .getContentLength()); Log.d(TAG, " HTTP res=" + httpConn .getResponseCode()); //httpConn.setInstanceFollowRedirects( false ); //httpConn.setRequestMethod( "HEAD" ); //conn.connect(); httpConn.disconnect(); Log.d(TAG, " HTTP ContentLength=" + httpConn .getContentLength()); Log.d(TAG, " HTTP res=" + httpConn .getResponseCode()); } } } } } } } } } } destHost = dest; } catch (IOException e) { Log.d(TAG, "got Excpetion " + e.toString()); } } else { } } catch (UnknownHostException e) { Log.d(TAG, "dns error" + e.toString()); destHost = null; } { if (null != destHost) { Log.d(TAG, "destHost=" + destHost); } } } }); thread.start(); try { thread.join(); { final String addr = (null == destHost) ? ("") : (destHost.toString()); final String reachable = (isReachable) ? ("reachable") : ("not reachable"); Toast toast = Toast.makeText(context, "DNS result=\n" + addr + "\n " + reachable, Toast.LENGTH_LONG); toast.show(); } } catch (InterruptedException e) { } } }); layout.addView(btn); } setContentView(layout); }
From source file:fr.cls.atoll.motu.processor.wps.TestServiceMetadata.java
public static void DetectProxy() throws Exception { System.setProperty("proxyHost", "proxy.cls.fr"); // adresse IP System.setProperty("proxyPort", "8080"); System.setProperty("socksProxyHost", "proxy.cls.fr"); // System.setProperty("http.proxyHost", "http-proxy.ece.fr"); // System.setProperty("http.proxyPort", "3128"); // System.setProperty("java.net.useSystemProxies", "true"); // List<Proxy> proxyList = ProxySelector.getDefault().select(new URI("http://schemas.opengis.net")); List<Proxy> proxyList = ProxySelector.getDefault().select(new URI("http://opendap.aviso.oceanobs.com")); for (Proxy proxy : proxyList) { System.out.println("Proxy type : " + proxy.type()); InetSocketAddress addr = (InetSocketAddress) proxy.address(); if (addr == null) { System.out.println("DIRECT CONXN"); } else {/*www . j a va 2 s . co m*/ System.out.println("Proxy hostname : " + addr.getHostName() + ":" + addr.getPort()); } } }
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/* ww w . j a v a 2 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:org.eclipse.mylyn.commons.sdk.util.CommonTestUtil.java
public static void dumpSystemInfo(PrintStream out) { Properties p = System.getProperties(); if (Platform.isRunning()) { p.put("build.system", Platform.getOS() + "-" + Platform.getOSArch() + "-" + Platform.getWS()); } else {/* www. ja v a 2s . c om*/ p.put("build.system", "standalone"); } String info = "System: ${os.name} ${os.version} (${os.arch}) / ${build.system} / ${java.vendor} ${java.vm.name} ${java.version}"; for (Entry<Object, Object> entry : p.entrySet()) { info = info.replaceFirst(Pattern.quote("${" + entry.getKey() + "}"), entry.getValue().toString()); } out.println(info); out.print("HTTP Proxy : " + WebUtil.getProxyForUrl("http://mylyn.org") + " (Platform)"); try { out.print(" / " + ProxySelector.getDefault().select(new URI("http://mylyn.org")) + " (Java)"); } catch (URISyntaxException e) { // ignore } out.println(); out.print("HTTPS Proxy : " + WebUtil.getProxyForUrl("https://mylyn.org") + " (Platform)"); try { out.print(" / " + ProxySelector.getDefault().select(new URI("https://mylyn.org")) + " (Java)"); } catch (URISyntaxException e) { // ignore } out.println(); out.println(); }
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;//from w w w. j av a 2s. c o m } 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:net.oddsoftware.android.feedscribe.data.FeedManager.java
void downloadFeedHttp(Feed feed, FeedStatus feedStatus, ArrayList<FeedItem> feedItems, ArrayList<Enclosure> enclosures) { try {/*from w w w . j a v a2 s . co m*/ // 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); } }
From source file:nl.armatiek.xslweb.configuration.WebApp.java
public CloseableHttpClient getHttpClient() { if (httpClient == null) { PoolingHttpClientConnectionManager cm; if (Context.getInstance().getTrustAllCerts()) { try { SSLContextBuilder scb = SSLContexts.custom(); scb.loadTrustMaterial(null, new TrustStrategy() { @Override/* w w w .j a v a 2 s . c o m*/ public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException { return true; } }); SSLContext sslContext = scb.build(); SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder .<ConnectionSocketFactory>create().register("https", sslsf) .register("http", new PlainConnectionSocketFactory()).build(); cm = new PoolingHttpClientConnectionManager(socketFactoryRegistry); } catch (Exception e) { logger.warn("Could not set HttpClient to trust all SSL certificates", e); cm = new PoolingHttpClientConnectionManager(); } } else { cm = new PoolingHttpClientConnectionManager(); } cm.setMaxTotal(200); cm.setDefaultMaxPerRoute(20); HttpHost localhost = new HttpHost("localhost", 80); cm.setMaxPerRoute(new HttpRoute(localhost), 50); HttpClientBuilder builder = HttpClients.custom().setConnectionManager(cm); builder.setRoutePlanner(new SystemDefaultRoutePlanner(ProxySelector.getDefault())); builder.setDefaultCookieStore(new BasicCookieStore()); httpClient = builder.build(); } return httpClient; }