apache httpclient using proxy

https:‮//‬www.theitroad.com

Apache HttpClient supports the use of a proxy server to connect to remote HTTP servers. Here's an example that demonstrates how to configure Apache HttpClient to use a proxy server:

import org.apache.http.HttpHost;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.DefaultProxyRoutePlanner;
import org.apache.http.util.EntityUtils;

public class HttpClientExample {
    public static void main(String[] args) throws Exception {
        HttpHost proxy = new HttpHost("proxy.example.com", 8080);
        DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy);
        CloseableHttpClient httpClient = HttpClients.custom()
            .setRoutePlanner(routePlanner)
            .build();
        HttpGet httpGet = new HttpGet("http://www.example.com");
        String responseBody = EntityUtils.toString(httpClient.execute(httpGet).getEntity());
        System.out.println(responseBody);
    }
}

In this example, we create an instance of HttpHost that represents the proxy server and configure it with the proxy host name and port number. We then create an instance of DefaultProxyRoutePlanner using the HttpHost object, and set it as the route planner for the CloseableHttpClient object using the setRoutePlanner() method. Finally, we execute an HTTP GET request using the CloseableHttpClient object, and extract the response body using the EntityUtils class.

Note that you can also configure the proxy server credentials by creating an instance of CredentialsProvider and setting it on the HttpClient object. You can find more information about using proxies with Apache HttpClient in the documentation.