Skip to content

How to use a proxy in every major programming language

By the ProxyOnly team · 16 Nov 2026 · 5 min read

Working proxy code with a login for curl, Python, Node.js, Java, C#, PHP and Ruby, each one run through a test proxy, with the setting that trips people up in each language.

Every HTTP client can use a proxy, but each one spells it differently, and several have a trap that turns a working proxy into a confusing error. This page gives working code for the common languages, each sending an HTTPS request through a proxy that requires a username and password.

We ran every example on 16 November 2026 against a test proxy on our own machine at 127.0.0.1:8101, with the username demo and the password s3cret. Each one printed a 200 status. Replace those three values with the host, port, username and password from your order page. Keep the proxy scheme http:// even though the site is HTTPS, because the client talks plain HTTP to the proxy and asks it to open a tunnel.

curl

curl -s -o /dev/null -w "%{http_code}\n" -x http://127.0.0.1:8101 -U demo:s3cret https://httpbin.org/ip

-U takes the password as typed, so special characters need no encoding. What is curl covers the other proxy options.

Python: Requests

import requests
proxy = "http://demo:s3cret@127.0.0.1:8101"
r = requests.get("https://httpbin.org/ip", proxies={"http": proxy, "https": proxy}, timeout=20)
print(r.status_code)

The trap: an HTTPS_PROXY environment variable overrides proxies set on a Session through session.proxies. Pass proxies= on each request, as here. Our Python Requests guide shows the test.

Python: httpx

import httpx
with httpx.Client(proxy="http://demo:s3cret@127.0.0.1:8101", timeout=20) as client:
    print("httpx", client.get("https://httpbin.org/ip").status_code)

The trap: httpx 0.28 takes a single proxy= argument. The older proxies= argument that many tutorials still show raised TypeError: Client.__init__() got an unexpected keyword argument 'proxies' in our test.

Python: aiohttp

import asyncio
import ssl
import aiohttp
import certifi
async def main():
    ssl_context = ssl.create_default_context(cafile=certifi.where())
    async with aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=20)) as session:
        async with session.get("https://httpbin.org/ip", proxy="http://demo:s3cret@127.0.0.1:8101", ssl=ssl_context) as r:
            print("aiohttp", r.status)
asyncio.run(main())

The traps: aiohttp 3.14 warned that the separate proxy_auth argument is deprecated, so put the login in the proxy URL as above. And on our Mac's python.org build of Python, aiohttp failed certificate checks until we passed an SSL context built from certifi. That is a local setup issue, not a proxy problem, and the same context does no harm elsewhere.

Node.js

Node's built-in fetch ignores proxy environment variables unless you start Node with NODE_USE_ENV_PROXY=1. With it, this worked on Node 24.12:

NODE_USE_ENV_PROXY=1 HTTPS_PROXY=http://demo:s3cret@127.0.0.1:8101 node app.mjs
const res = await fetch("https://httpbin.org/ip", { signal: AbortSignal.timeout(20000) });
console.log("node fetch", res.status);

To choose a proxy in code, or different proxies for different requests, use undici's ProxyAgent. We ran it with undici 8.12.

import { fetch, ProxyAgent } from "undici";
const dispatcher = new ProxyAgent("http://demo:s3cret@127.0.0.1:8101");
const res = await fetch("https://httpbin.org/ip", { dispatcher, signal: AbortSignal.timeout(20000) });
console.log("undici", res.status);

When a Node request fails, the useful message is in the error's cause, often two levels down. Every common proxy error shows how to print it.

Java

Java's built-in HttpClient takes a ProxySelector and an Authenticator. This runs as a single file with java ProxyDemo.java on Java 11 or later. We used Java 21.

import java.net.Authenticator;
import java.net.InetSocketAddress;
import java.net.PasswordAuthentication;
import java.net.ProxySelector;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
public class ProxyDemo {
    public static void main(String[] args) throws Exception {
        HttpClient client = HttpClient.newBuilder()
            .proxy(ProxySelector.of(new InetSocketAddress("127.0.0.1", 8101)))
            .authenticator(new Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication("demo", "s3cret".toCharArray());
                }
            })
            .build();
        HttpRequest request = HttpRequest.newBuilder(URI.create("https://httpbin.org/ip")).build();
        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
        System.out.println("java " + response.statusCode());
    }
}

The trap is the biggest on this page. Run as it is, the code printed java 407. The JDK's own net.properties file sets jdk.http.auth.tunneling.disabledSchemes=Basic, and its comment explains that Basic sends the password effectively in clear text, so Java refuses to use it for HTTPS tunnels. Proxy logins with a username and password normally use Basic. Clearing the property fixed it:

java -Djdk.http.auth.tunneling.disabledSchemes= ProxyDemo.java

That printed java 200. You can also set the property in code with System.setProperty before the first request. Make the change knowingly: the password crosses the network to the proxy in a form anyone on the path can decode, so use the proxy from networks you trust.

C# and .NET

using System.Net;
var handler = new HttpClientHandler
{
    Proxy = new WebProxy("http://127.0.0.1:8101") { Credentials = new NetworkCredential("demo", "s3cret") },
    UseProxy = true,
};
using var client = new HttpClient(handler) { Timeout = TimeSpan.FromSeconds(20) };
var response = await client.GetAsync("https://httpbin.org/ip");
Console.WriteLine($"csharp {(int)response.StatusCode}");

We ran this as Program.cs in a new console project on the .NET 6 SDK with dotnet run. Create the HttpClient once and reuse it, rather than once per request.

PHP

<?php
$ch = curl_init("https://httpbin.org/ip");
curl_setopt($ch, CURLOPT_PROXY, "http://127.0.0.1:8101");
curl_setopt($ch, CURLOPT_PROXYUSERPWD, "demo:s3cret");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 20);
curl_exec($ch);
echo "php ", curl_getinfo($ch, CURLINFO_HTTP_CODE), "\n";

PHP's curl extension uses the same library as the curl command, and CURLOPT_PROXYUSERPWD keeps the login out of the URL. We ran it on PHP 8.5.

Ruby

require "net/http"
http = Net::HTTP.new("httpbin.org", 443, "127.0.0.1", 8101, "demo", "s3cret")
http.use_ssl = true
http.read_timeout = 20
response = http.get("/ip")
puts "ruby #{response.code}"

Net::HTTP.new takes the proxy address, port, username and password after the site's host and port. We ran it on Ruby 2.6.

Go

Go was not installed on our test machine, so we did not run this. It follows the net/http documentation, where a Transport takes a Proxy function and http.ProxyURL builds one from a URL that can carry the login.

package main
import (
	"fmt"
	"net/http"
	"net/url"
	"time"
)
func main() {
	proxyURL, _ := url.Parse("http://demo:s3cret@127.0.0.1:8101")
	client := &http.Client{Transport: &http.Transport{Proxy: http.ProxyURL(proxyURL)}, Timeout: 20 * time.Second}
	resp, err := client.Get("https://httpbin.org/ip")
	if err != nil {
		panic(err)
	}
	defer resp.Body.Close()
	fmt.Println("go", resp.StatusCode)
}

Rules that apply in every language

  • Keep the proxy scheme http:// for an HTTP proxy, even for HTTPS sites.
  • Percent-encode special characters in a password that sits inside a URL, or use the client's separate username and password setting.
  • Set a timeout. Several clients wait for minutes, or forever, by default.
  • Read credentials from environment variables or a secrets store, not from code you commit.
  • To spread requests across several proxies, keep a list and choose one per request. Each of our proxies is one address with its own host, port and login.

Our integration guides cover more tools, and if a request fails, every common proxy error maps the message to its cause.

Try it yourself

Create an account, add funds from US$1 and order a proxy in the country you need.

Keep reading