> For the complete documentation index, see [llms.txt](https://dinproxy.gitbook.io/docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://dinproxy.gitbook.io/docs/guides/residential-proxies/code-examples.md).

# Code examples

Use residential proxies from Node.js, Python, cURL, Java, C#, PHP, Go and Ruby.

Replace `1024~myuser` and `YOUR_PASSWORD` with your [proxy user](https://dinproxy.gitbook.io/docs/getting-started/proxy-users.md). Add [location and session options](https://dinproxy.gitbook.io/docs/guides/residential-proxies/location-and-sessions.md) to the username as needed. Residential proxies use port `7777`; for mobile proxies see the [mobile code examples](https://dinproxy.gitbook.io/docs/guides/mobile-proxies/code-examples.md).

{% tabs %}
{% tab title="Node.js" %}

```javascript
// npm install undici
// Save as test.mjs and run: node test.mjs
import { fetch, ProxyAgent } from "undici";

const username = "1024~myuser@country=us";
const password = "YOUR_PASSWORD";
const token = Buffer.from(`${username}:${password}`).toString("base64");

const dispatcher = new ProxyAgent({
  uri: "http://proxy.dinproxy.com:7777",
  token: `Basic ${token}`,
});

const response = await fetch("https://httpbin.org/ip", { dispatcher });
console.log(await response.text());
```

{% endtab %}

{% tab title="Python" %}

```python
# pip install requests
from urllib.parse import quote
import requests

username = "1024~myuser@country=us"
password = "YOUR_PASSWORD"
# Characters such as "@" must be percent-encoded inside a proxy URL.
proxy = f"http://{quote(username, safe='')}:{quote(password, safe='')}@proxy.dinproxy.com:7777"

response = requests.get(
    "https://httpbin.org/ip",
    proxies={"http": proxy, "https": proxy},
    timeout=30,
)
print(response.text)
```

For SOCKS5, install `requests[socks]` and use `socks5h://` instead of `http://`.
{% endtab %}

{% tab title="cURL" %}

```bash
# HTTP proxy
curl --proxy 'http://proxy.dinproxy.com:7777' \
  --proxy-user '1024~myuser@country=us:YOUR_PASSWORD' \
  'https://httpbin.org/ip'

# SOCKS5 (the proxy resolves host names)
curl --proxy 'socks5h://proxy.dinproxy.com:7777' \
  --proxy-user '1024~myuser@country=us:YOUR_PASSWORD' \
  'https://httpbin.org/ip'
```

In Windows PowerShell, write it on one line with `curl.exe`:

```powershell
curl.exe --proxy 'http://proxy.dinproxy.com:7777' --proxy-user '1024~myuser@country=us:YOUR_PASSWORD' 'https://httpbin.org/ip'
```

{% endtab %}

{% tab title="Java" %}

```java
// Java 11+. Save as Main.java and run: java Main.java
import java.net.InetSocketAddress;
import java.net.ProxySelector;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.Base64;

public class Main {
    public static void main(String[] args) throws Exception {
        // Java drops proxy sign-ins for HTTPS sites unless this is cleared first.
        System.setProperty("jdk.http.auth.tunneling.disabledSchemes", "");
        String auth = Base64.getEncoder()
            .encodeToString("1024~myuser@country=us:YOUR_PASSWORD".getBytes(StandardCharsets.UTF_8));

        HttpClient client = HttpClient.newBuilder()
            .proxy(ProxySelector.of(new InetSocketAddress("proxy.dinproxy.com", 7777)))
            .build();
        HttpRequest request = HttpRequest.newBuilder(URI.create("https://httpbin.org/ip"))
            .header("Proxy-Authorization", "Basic " + auth)
            .timeout(Duration.ofSeconds(30))
            .build();
        System.out.println(client.send(request, HttpResponse.BodyHandlers.ofString()).body());
    }
}
```

The sign-in goes in the `Proxy-Authorization` header, so it travels with the first request. The location and session options then always arrive, also from a [whitelisted IP](https://dinproxy.gitbook.io/docs/getting-started/ip-whitelist.md).
{% endtab %}

{% tab title="C#" %}

```csharp
// .NET 6+
using System;
using System.Net;
using System.Net.Http;

var handler = new HttpClientHandler
{
    // SOCKS5 sends the proxy user at once; same host, port and sign-in as HTTP.
    Proxy = new WebProxy("socks5://proxy.dinproxy.com:7777")
    {
        Credentials = new NetworkCredential("1024~myuser@country=us", "YOUR_PASSWORD"),
    },
};

using var client = new HttpClient(handler) { Timeout = TimeSpan.FromSeconds(30) };
Console.WriteLine(await client.GetStringAsync("https://httpbin.org/ip"));
```

SOCKS5 sends the username with the first request, so the location and session options always arrive, also from a [whitelisted IP](https://dinproxy.gitbook.io/docs/getting-started/ip-whitelist.md). In .NET, write `socks5://` as above: the proxy still looks up the site's name.
{% endtab %}

{% tab title="PHP" %}

```php
<?php
// Requires the PHP cURL extension.
$curl = curl_init('https://httpbin.org/ip');
curl_setopt_array($curl, [
    CURLOPT_PROXY => 'http://proxy.dinproxy.com:7777', // or socks5h://
    CURLOPT_PROXYUSERPWD => '1024~myuser@country=us:YOUR_PASSWORD',
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_TIMEOUT => 30,
]);

$response = curl_exec($curl);
if ($response === false) {
    throw new RuntimeException(curl_error($curl));
}
echo $response;
```

{% endtab %}

{% tab title="Go" %}

```go
package main

import (
	"fmt"
	"io"
	"net/http"
	"net/url"
	"time"
)

func main() {
	proxy := &url.URL{
		Scheme: "http",
		User:   url.UserPassword("1024~myuser@country=us", "YOUR_PASSWORD"),
		Host:   "proxy.dinproxy.com:7777",
	}
	client := &http.Client{
		Timeout:   30 * time.Second,
		Transport: &http.Transport{Proxy: http.ProxyURL(proxy)},
	}

	response, err := client.Get("https://httpbin.org/ip")
	if err != nil {
		panic(err)
	}
	defer response.Body.Close()

	body, err := io.ReadAll(response.Body)
	if err != nil {
		panic(err)
	}
	fmt.Println(string(body))
}
```

{% endtab %}

{% tab title="Ruby" %}

```ruby
require 'net/http'

uri = URI('https://httpbin.org/ip')
http = Net::HTTP.new(uri.host, uri.port, 'proxy.dinproxy.com', 7777, '1024~myuser@country=us', 'YOUR_PASSWORD')
http.use_ssl = true
http.read_timeout = 30

puts http.request(Net::HTTP::Get.new(uri)).body
```

{% endtab %}
{% endtabs %}

## Sticky session in Python

Keep one IP for a series of requests by reusing a session ID:

```python
from urllib.parse import quote
import requests, uuid

session_id = uuid.uuid4().hex[:12]
username = f"1024~myuser@country=us@session={session_id}@time=10"
proxy = f"http://{quote(username, safe='')}:{quote('YOUR_PASSWORD', safe='')}@proxy.dinproxy.com:7777"

with requests.Session() as s:
    s.proxies = {"http": proxy, "https": proxy}
    for _ in range(3):
        print(s.get("https://httpbin.org/ip", timeout=30).text)  # same IP each time
```

## Testing

`https://httpbin.org/ip` and `https://ipinfo.io/json` show the IP (and location) the target site sees. If a request fails, the proxy's answer names the reason: see [Errors & troubleshooting](https://dinproxy.gitbook.io/docs/guides/errors-and-troubleshooting.md).
