views:

387

answers:

1

I'm trying to use the latest (4.0.1) Apache http core components library. However, my web browser goes through a proxy - suppose it is myproxy.com:9191. Could someone provide some sample code for getting a simple http get to use this as a proxy?

I've tried adding the following at the beginning of my code, but had no joy:

ProxySelector.setDefault(new ProxySelector() {
  public List<Proxy> select(URI uri) {
    Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("myproxy.com", 9191);
    return Arrays.asList(new Proxy[]{proxy)});
  }
  public void connectFailed(URI uri, SocketAddress sa, IOException ioe) {
    ioe.printStackTrace();
  }
});
+2  A: 

In the absence of an answer, here's what I found out.

Firstly, for this sort of thing, you don't just want to use the http core library, you want to use httpclient as well, make sure you download both from the download page.

Secondly, use this code:

DefaultHttpClient httpclient = new DefaultHttpClient();
HttpHost proxy = new HttpHost("myproxy.com", 9191);
httpclient.getCredentialsProvider().setCredentials(
  new AuthScope(PROXY, PROXY_PORT),
  new UsernamePasswordCredentials("username", "password"));
httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
Nick Fortescue
I'm not liking HttpCore much. The API seems better thought out than HttpClient, but it's unpleasant in a whole new set of ways, and not as easy to use as HttpClient.
skaffman
my understanding is that if you need to do httpClient type things, you use HttpClient, and that in turn uses HttpCore for some more abstract things. Most apps probably don't need to use HttpCore directly. Or am I wrong?
matt b