Java Proxy Authentication with HttpClient and Authenticator
To use RotatingProxy in Java, configure an HttpClient with a java.net.Proxy and an Authenticator for the gateway host gw.rotatingproxy.cc on port 7070 for HTTP or 7071 for SOCKS5. All targeting and session options are passed through the proxy username, while the password is your proxy user's password.
- Use java.net.Proxy and Authenticator for HTTP and SOCKS5 proxy authentication.
- Pass country, city, and session ID options in the proxy username string.
- Disable the HttpClient's default system proxy selector to avoid conflicts.
- Verify the exit IP with a simple HTTP request to confirm the proxy works.
Java Proxy Authentication with HttpClient
Java proxy authentication is handled by the java.net.Authenticator class and a configured java.net.Proxy object when building an HttpClient. The standard approach works with both HTTP and SOCKS5 proxies, making it suitable for integrating with our rotating proxy gateway. You will set the proxy host to gw.rotatingproxy.cc and use either port 7070 for HTTP CONNECT or port 7071 for SOCKS5. Authentication credentials, along with all targeting options like network type and location, are embedded in the username field, following our specific grammar. This method is essential for tasks like web scraping and price monitoring where reliable IP rotation is needed.
Where to Configure Proxy Settings in Java
Proxy settings in Java are configured at the HTTP client level, not globally for the JVM, giving you fine-grained control per client instance. You create a Proxy instance and pass it to the HttpClient.Builder. It is crucial to also disable the client's default behavior of using the system-wide proxy settings, which can cause conflicts and prevent your explicit proxy from being used. This is done by calling .proxy(ProxySelector.of(null)) on the builder. For applications that make requests through multiple channels (like using both direct and proxied connections), you should create separate HttpClient instances with their own proxy configurations. This isolation is a best practice for concurrency planning in crawlers.
HTTP Proxy Setup on Port 7070
To set up an HTTP proxy on port 7070, you create a Proxy object of type Proxy.Type.HTTP and provide it to the HttpClient builder along with a custom Authenticator. The authenticator will supply the username and password for each request. Here is a concrete example for making a simple GET request through the rotating residential network.
import java.net.*;
import java.net.http.*;
import java.net.http.HttpResponse.BodyHandlers;
import java.time.Duration;
public class RotatingProxyExample {
public static void main(String[] args) throws Exception {
String proxyUser = "USERNAME_net.res_cc.us";
String proxyPass = "PASSWORD";
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("gw.rotatingproxy.cc", 7070));
Authenticator authenticator = new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
if (getRequestorType() == Authenticator.RequestorType.PROXY) {
return new PasswordAuthentication(proxyUser, proxyPass.toCharArray());
}
return null;
}
};
HttpClient client = HttpClient.newBuilder()
.proxy(ProxySelector.of(null)) // Disable system proxy
.proxy(proxy)
.authenticator(authenticator)
.connectTimeout(Duration.ofSeconds(30))
.build();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://httpbin.org/ip"))
.timeout(Duration.ofSeconds(30))
.build();
HttpResponse<String> response = client.send(request, BodyHandlers.ofString());
System.out.println("Exit IP: " + response.body());
}
}
This code constructs a client that routes all traffic through the HTTP proxy gateway. The Authenticator checks if the authentication request is for the proxy and then returns the credentials. Note the use of ProxySelector.of(null) to ensure no other proxy settings interfere. This setup is the foundation for using proxies in Java for data collection from sources like Google search or Amazon.
SOCKS5 Proxy Setup on Port 7071
Java's HttpClient fully supports SOCKS5 proxies, which you can use by creating a Proxy object of type Proxy.Type.SOCKS and pointing it to port 7071. The authentication mechanism remains identical to the HTTP proxy setup. SOCKS5 can be beneficial in certain network configurations as it operates at a lower level, but for most HTTP/HTTPS traffic, both ports work equally well. Here is how to modify the previous example for SOCKS5.
// Change only the Proxy object creation
Proxy proxy = new Proxy(Proxy.Type.SOCKS, new InetSocketAddress("gw.rotatingproxy.cc", 7071));
// The HttpClient builder, Authenticator, and everything else stays the same.
HttpClient client = HttpClient.newBuilder()
.proxy(ProxySelector.of(null))
.proxy(proxy)
.authenticator(authenticator)
.connectTimeout(Duration.ofSeconds(30))
.build();
With this change, all connections from this client will use the SOCKS5 protocol. It is important to understand the differences, which we explain in our guide on HTTP vs SOCKS5 proxies. For tasks involving social media management or market research, either protocol is suitable.
Passing Targeting and Session Options in Username
All geo-targeting and session control is achieved by building a specific username string; the password remains your proxy user's static password. You construct the username by appending underscore-separated options to the proxy user's login. For example, to use a sticky session from the mobile network in Germany, targeting Berlin, you would build the following username.
String username = "USERNAME_net.mob_cc.de_city.berlin_sid.a7k2m9_ttl.20";
// Password is just "PASSWORD"
The sid (session ID) is any 6 to 16 character alphanumeric string you choose; reusing the same sid within the ttl (time-to-live in minutes) period will keep the same IP address. Omitting the sid option results in a new IP on every connection. For detailed rules, see our username options documentation. This flexibility is key for managing sessions in scrapers and for use cases like travel fare aggregation where maintaining a session might be necessary.
Verifying the Exit IP and Location
After configuring your proxy client, you should verify that requests are exiting from the expected IP and location. A simple way is to make a request to an IP echo service or a geolocation API. Using the client from the setup example, you can check against https://api.ipify.org for a plain IP response or https://ipinfo.io/json for a detailed JSON response including country and city. This verification step is crucial when setting up proxies for checking geo-restricted content or rank tracking. If the returned location does not match your targeting, double-check the username options for typos. For more tools, visit our IP check tools page.
Fixing Common Proxy Errors in Java
Java applications using proxies can encounter several common errors. A 407 Proxy Authentication Required error shows the proxy did not accept your login. This usually means the username or password is incorrect, or the username string is malformed. Ensure your proxy user is active and has access to the chosen network (e.g., net.mob). Check our error 407 guide for more details. Connection timeouts can occur if the target server is slow or if your connection pool is exhausted. Increase the connectTimeout and timeout values in your HttpClient builder. Timeouts can also happen if the proxy gateway cannot allocate an IP from the requested location; verify the location is available in our coverage list. TLS/SSL handshake errors sometimes appear when the target site uses strict TLS fingerprinting. Using the standard Java HttpClient is generally fine, but if you encounter issues, ensure you are not using an outdated Java version. For advanced TLS issues, refer to our guide on TLS and proxies.
Tips for Running at Scale with Java
When running a high-volume crawler, efficient resource management is critical. Use a single HttpClient instance per proxy configuration (or a small pool of them) and reuse it for many requests, as it manages its own connection pool internally. Configure the connection pool size via HttpClient.Builder methods like .executor() and manage concurrency within the limits described in our concurrency limit help page. Implement a solid retry strategy with exponential backoff for temporary failures (like 502 errors). Rotate session IDs logically for tasks that need fresh IPs, and consider using different proxy users for different threads to isolate traffic caps. To manage costs, monitor your usage and understand how pay as you go proxy billing works, especially the monthly volume rates. For large-scale projects like AI training data collection, these practices help maintain stability and cost-efficiency.
Using Third-Party HTTP Clients (OkHttp, Apache)
While Java's built-in HttpClient is excellent, you might be using a third-party library like OkHttp or Apache HttpClient. The configuration principles are similar: you provide the proxy host, port, and credentials. For OkHttp, you create a Proxy instance and an Authenticator much like the standard Java example. For Apache HttpClient, you use HttpHost for the proxy and CredentialsProvider. Always consult the current library documentation for the exact syntax, as details can change between versions. The key constant is our gateway address (gw.rotatingproxy.cc) and the username/password format. If you are integrating with a headless browser for mobile app testing, you might need to configure the proxy at the browser level instead, as shown in our Playwright Node.js guide.
Disabling System Proxy and Scheme Conflicts
A common pitfall in Java proxy authentication is the HttpClient's default ProxySelector, which may automatically use the system's proxy settings (set via -Dhttp.proxyHost JVM arguments or environment variables). This can override or conflict with the proxy you explicitly set in code. To disable this behavior completely, you must call .proxy(ProxySelector.of(null)) on the HttpClient.Builder. This tells the client to use no proxy selector other than the one you explicitly provide via the .proxy(proxy) method. Failing to do this can lead to confusing behavior where some requests go through your proxy and others do not, especially when dealing with multiple request schemes (HTTP vs HTTPS). Ensuring a clean proxy configuration is a fundamental step for reliable website uptime and change monitoring.
Questions
Can I use the same HttpClient for both proxied and direct requests?
No, it is not recommended. Configure separate HttpClient instances: one with your proxy settings and another without any proxy or with a null ProxySelector. This keeps the routing clear and avoids accidental proxy usage for direct calls.
How do I target a specific US state like California?
Append the options <code>_cc.us_st.ca</code> to your username. The state code must be the two-letter abbreviation (e.g., <code>st.ny</code> for New York). This only works with the <code>cc.us</code> country code. See our US state targeting guide for details.
My Java app works without proxy but hangs with the proxy. What's wrong?
This is often a timeout issue. The default timeouts may be too short for the proxy handshake and IP allocation. Increase the connect and read timeouts in your HttpClient builder to 30 or 60 seconds. Also, verify your network allows outbound connections to ports 7070 and 7071.
How do I change the IP address for every single request?
Do not include a <code>sid</code> (session ID) option in your username. Every new connection the HttpClient opens will then receive a fresh IP from the chosen network and location. For fine-grained control, you can also change the username string for each request.
Is there a way to see how much traffic my Java application has used?
Yes, you can check your usage in the dashboard, which breaks down traffic by proxy user, network, and day. For programmatic access, use our REST API with an API key (see creating an API key) to fetch balance and usage metrics.
I'm getting a "TLS handshake failure" through the proxy. How can I fix it?
First, ensure you are using a recent Java version (Java 11 or later). The issue might be with the target site's TLS configuration. Try setting the HttpClient to use a more compatible TLS version via <code>SSLParameters</code>. If the problem persists, test with a different target URL to isolate the issue.
Start with one top-up, use any network
Create an account in a minute, add $40 or more, and the same balance pays for residential, mobile, datacenter and ISP traffic.