How to Use a Proxy in Go and Java: Practical Setup Guide
A practical developer guide to configuring HTTP and HTTPS proxies in Go and Java, including authentication, rotation, errors, and connection reuse.
Setting a proxy in Go or Java usually takes only a few lines of code. In Go, configure the Transport.Proxy field on an http.Client. In Java, create a Proxy object or configure the HTTP client with a proxy address. For authenticated proxies, credentials normally need to be supplied separately through headers or an authenticator.
When you start sending automated HTTP requests, adding a proxy is often one of the first infrastructure changes you need. A proxy can route requests through another IP address, separate scraping traffic from your primary network, or let different workers use different endpoints.
The basic setup is simple in both Go and Java. The bigger challenge is making sure authentication, timeouts, HTTPS requests, and connection reuse behave correctly.
This guide covers practical implementations for both languages.
How Do You Set a Proxy in Go?
Go’s standard net/http package supports proxies directly through http.Transport.
Here is a minimal example:
package main
import (
"fmt"
"io"
"net/http"
"net/url"
)
func main() {
proxyURL, _ := url.Parse("http://127.0.0.1:8080")
transport := &http.Transport{
Proxy: http.ProxyURL(proxyURL),
}
client := &http.Client{
Transport: transport,
}
resp, err := client.Get("https://httpbin.org/ip")
if err != nil {
panic(err)
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
fmt.Println(string(body))
}The important part is the custom Transport.
Instead of allowing Go to connect directly to the destination server, http.ProxyURL() tells the transport to send requests through the specified proxy.
This approach works well when one client consistently uses one proxy endpoint.
How Do You Use Proxy Authentication in Go?
Many commercial proxy services require a username and password.
The easiest option is to include the credentials in the proxy URL:
proxyURL, _ := url.Parse(
"http://username:password@proxy.example.com:8000",
)Then use that URL with the same transport configuration:
transport := &http.Transport{
Proxy: http.ProxyURL(proxyURL),
}Go will handle the proxy authorization information during the connection.
Avoid hardcoding production credentials directly into your source code. Environment variables or secret-management systems are safer choices.
For example:
proxyUser := os.Getenv("PROXY_USER")
proxyPass := os.Getenv("PROXY_PASS")This also makes it easier to deploy the same application across development, staging, and production environments.
How Do You Set a Proxy in Java?
Java has supported proxies for years, but the exact setup depends on which HTTP client you use.
For Java’s standard networking classes, you can create a Proxy object:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.*;
public class ProxyExample {
public static void main(String[] args) throws Exception {
Proxy proxy = new Proxy(
Proxy.Type.HTTP,
new InetSocketAddress("127.0.0.1", 8080)
);
URL url = new URL("https://httpbin.org/ip");
HttpURLConnection connection =
(HttpURLConnection) url.openConnection(proxy);
BufferedReader reader = new BufferedReader(
new InputStreamReader(connection.getInputStream())
);
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
reader.close();
}
}The proxy is applied specifically to that connection.
This is often preferable to changing JVM-wide proxy settings because other parts of your application can continue connecting normally.
How Do You Configure a Proxy With Java HttpClient?
Modern Java applications can use java.net.http.HttpClient.
A proxy can be configured like this:
import java.net.*;
import java.net.http.*;
public class Main {
public static void main(String[] args) throws Exception {
HttpClient client = HttpClient.newBuilder()
.proxy(
ProxySelector.of(
new InetSocketAddress("127.0.0.1", 8080)
)
)
.build();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://httpbin.org/ip"))
.GET()
.build();
HttpResponse<String> response =
client.send(
request,
HttpResponse.BodyHandlers.ofString()
);
System.out.println(response.body());
}
}For most modern Java projects, this API provides a cleaner approach than older HttpURLConnection code.
How Does Proxy Authentication Work in Java?
Java can provide credentials through an Authenticator.
For example:
Authenticator authenticator = new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(
"username",
"password".toCharArray()
);
}
};It can then be attached to the HTTP client:
HttpClient client = HttpClient.newBuilder()
.proxy(
ProxySelector.of(
new InetSocketAddress("proxy.example.com", 8000)
)
)
.authenticator(authenticator)
.build();One detail worth remembering is that destination-server authentication and proxy authentication can interact with the same authentication mechanisms.
Test the behavior against your actual proxy service rather than assuming every provider handles authentication identically.
Should You Use Environment Proxy Variables in Go?
Go provides built-in support for environment-based proxy configuration through:
http.ProxyFromEnvironmentFor example:
transport := &http.Transport{
Proxy: http.ProxyFromEnvironment,
}Your application can then use environment variables such as:
HTTP_PROXY
HTTPS_PROXY
NO_PROXYThis is useful for infrastructure where proxy settings change between deployments.
If your application needs to rotate proxies request by request, however, explicit proxy selection normally gives you more control.
Developers coming from Python may notice that the concept is similar even though the client syntax differs. This simple guide to using a proxy in Python shows the same underlying pattern: configure a proxy endpoint, attach it to the HTTP client, and verify the outgoing IP.
How Do You Rotate Proxies in Go?
A basic rotation strategy stores several proxy URLs and chooses one for each request or worker.
Get ProxiesThatWork’s stories in your inbox
Join Medium for free to get updates from this writer.
For example:
proxies := []string{
"http://proxy1.example.com:8000",
"http://proxy2.example.com:8000",
"http://proxy3.example.com:8000",
}You could select proxies randomly or sequentially.
For high-volume applications, creating a new transport for every request is rarely ideal. Connection pools and keep-alive behavior matter.
A better design is often to create one reusable client per proxy and distribute requests among those clients.
That allows Go to reuse TCP connections while still distributing traffic across IP addresses.
How Do You Rotate Proxies in Java?
The same principle applies to Java.
Instead of repeatedly rebuilding HttpClient objects, create a small pool of clients, with each client configured for a different proxy.
Your application can then choose a client based on:
- round-robin rotation;
- target domain;
- previous response status;
- current error rate;
- request volume; or
- session requirements.
For scraping systems, random rotation is not always the best strategy.
Some websites associate multiple requests with one session. Changing IP addresses halfway through a session can actually increase suspicious behavior.
Session-aware rotation is often more reliable.
What Proxy Errors Should Go and Java Developers Watch For?
A correctly configured client can still fail because of the proxy itself.
Common issues include:
HTTP 407 Proxy Authentication Required
The proxy received your request but rejected or did not receive valid authentication credentials.
Check the username, password, authentication format, and proxy endpoint.
Connection refused
The host or port may be incorrect, unavailable, or blocked by a firewall.
Connection timeout
The proxy may be overloaded, geographically distant, or temporarily unreachable.
TLS or certificate errors
HTTPS traffic normally uses the HTTP CONNECT method through an HTTP proxy.
Unexpected TLS interception, certificate problems, or unusual proxy configurations can cause certificate validation failures.
HTTP 403 or 429 responses
These responses may come from the target website rather than the proxy.
A working proxy connection does not automatically mean the destination accepts your automated requests.
What Should You Look for in a Proxy for Go or Java Applications?
The programming language rarely determines which proxy service you need. Your workload matters more.
For development and scraping projects, consider:
- HTTP and HTTPS support;
- stable authentication;
- sufficient concurrent connections;
- predictable latency;
- clean IP reputation;
- simple endpoint formatting; and
- enough IP capacity for your request volume.
Large enterprise proxy networks can make sense when you need residential geolocation or massive IP diversity. For straightforward automation and datacenter workloads, cheap proxies with stable endpoints may be more practical than paying for features your application never uses.
Go vs Java: Which Is Better for Proxy-Based Requests?
Both languages handle proxies well.
Go has an especially compact HTTP networking stack and makes it easy to build highly concurrent request workers. Its http.Transport abstraction also gives developers detailed control over connection pooling.
Java has a mature networking ecosystem and works well for larger applications already built around JVM frameworks and services.
If you are starting a lightweight crawler from scratch, Go may require less code.
If your scraping, monitoring, or data-processing infrastructure already runs in Java, switching languages purely for proxy support offers little benefit.
The proxy itself is simply another network layer.
Final Takeaway
You do not need a special proxy library to get started with Go or Java.
In Go, configure http.Transport and attach it to an http.Client. In modern Java, configure HttpClient with a ProxySelector. Add authentication when required, set sensible timeouts, and test the outgoing IP before scaling.
Once basic connectivity works, focus on the issues that matter more in production: connection reuse, proxy health, retries, rotation strategy, and session consistency.
Those decisions usually have a much larger effect on reliability than the few lines of code required to enable the proxy itself.










