Network proxies are becoming commonplace these days, they even appear in some home networks. For that reason there is an increasing need to support connecting through a proxy. Of course we’d want that in an aggregator too, so here goes.
In Eclipse we have shared proxy settings (General > Network Connections) that we should be using to obtain the required information for setting up a network connection.
First we implement the method that obtains the Eclipse proxy service. Notice that we’ll wait for the org.eclipse.core.net bundle to become active. If a user name and password is assigned to the proxy, Equinox Security Manager will ask you for a password before the bundle becomes active. It may take a while before everything is ready and the default timeout for obtaining the service is five seconds. So unless we wait it’s quite likely that would not get the service before it times out.
private static final String CORE_NET_BUNDLE = "org.eclipse.core.net"; public IProxyService getProxyService() { Bundle bundle = Platform.getBundle(CORE_NET_BUNDLE); while (bundle.getState() != Bundle.ACTIVE) { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } ServiceReference ref = bundle.getBundleContext().getServiceReference(IProxyService.class.getName()); if (ref != null) { return (IProxyService) bundle.getBundleContext().getService(ref); } return null; }
Next we’ll set up the proxy for the connection and use it. This is simply a matter of getting the required IProxyData. If it’s null we’re not going to need a proxy. Next we create the connection and specify credentials as required.
IProxyData proxyData = null; URLConnection yc = null; IProxyService service = getProxyService(); if (service != null && service.isProxiesEnabled()) { proxyData = service.getProxyDataForHost(feed.getHost(), feed.getProtocol().toUpperCase()); } if (proxyData == null) { yc = feed.openConnection(); } else { InetSocketAddress sockAddr = new InetSocketAddress(InetAddress.getByName(proxyData.getHost()), proxyData.getPort()); Proxy proxy = new Proxy(Type.HTTP, sockAddr); yc = feed.openConnection(proxy); if (proxyData.isRequiresAuthentication()) { String proxyLogin = proxyData.getUserId()+ ":" + proxyData.getPassword(); yc.setRequestProperty("Proxy-Authorization", "Basic "+ EncodingUtils.encodeBase64(proxyLogin.getBytes())); } }
Note that while we’re using the proxy to download the feed data, it is not being used in XULRunner to download images and other media. More about that later.