Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

org.apache.http.impl.client.CloseableHttpClient Proxy Authentication

My application does https requests to different targets and now I have a proxy problem.

While the client is connecting to target, I get an 407 (Proxy Authentication Required) from the target server. To be clear: Client reaches other servers in www already.

How can I build the CloseableHttpClient in general to allow this proxy auth? Can someone give me a short example how to allow proxy auth?
Does double proxy auth (my proxy + external proxy) also works?

like image 930
heaphach Avatar asked Apr 01 '15 07:04

heaphach


1 Answers

See "Request configuration" section here. In short:

1.) Build your client:

RequestConfig defaultRequestConfig = RequestConfig.custom()
    .setSocketTimeout(5000)
    .setConnectTimeout(5000)
    .setConnectionRequestTimeout(5000)
    .setStaleConnectionCheckEnabled(true)
    .build();

CloseableHttpClient httpclient = HttpClients.custom()
    .(settingXY)
    .setDefaultCookieStore(defaultCookieStore)
    .setDefaultCredentialsProvider(defaultCredentialsProvider)
    .setDefaultRequestConfig(defaultRequestConfig)
    .setDefaultRequestConfig(defaultRequestConfig)
    .build();
//You dont need to specify proxy here!!!

2.) Then build your reqeuest(s) like this:

HttpGet httpget = new HttpGet("http://www.apache.org/");
RequestConfig requestConfig = RequestConfig.copy(defaultRequestConfig)
    .setProxy(new HttpHost("myproxy", 8080))
    .build();
httpget.setConfig(requestConfig);

3.) Then

defaultCredentialsProvider.setCredentials(new AuthScope(proxy.getHostName(), proxy.getPort()), proxyCredentials);

HttpGet httpget = new HttpGet("http://www.apache.org/");
HttpUriRequest request= httpget;
CloseableHttpResponse response = httpclient.execute(request, context);

Hope this helps someone.

like image 172
heaphach Avatar answered Oct 28 '22 06:10

heaphach