# 常用客户端的可运行示例。

每段代码都通过美国住宅出口请求 `https://api.ipify.org` 并输出 IP。只需替换用户名参数和目标地址，其余内容无需更改。


## 命令行

**cURL**

```curl
# HTTP(S) 代理
curl -x http://USER-cc-us:PASS@res.proxshift.com:9000 https://api.ipify.org

# 使用远程 DNS 的 SOCKS5
curl --proxy socks5h://USER-cc-us:PASS@res.proxshift.com:9001 https://api.ipify.org

# 固定会话 30 分钟，并输出详细信息以查看 CONNECT
curl -v -x http://USER-cc-us-sid-a1b2c3-ttl-30m:PASS@res.proxshift.com:9000 https://api.ipify.org
```

**wget**

```wget
https_proxy=http://USER-cc-us:PASS@res.proxshift.com:9000 \
http_proxy=http://USER-cc-us:PASS@res.proxshift.com:9000 \
wget -qO- https://api.ipify.org
```

**环境变量**

```env
# 大多数命令行工具和许多库都会读取这些变量
export HTTP_PROXY=http://USER-cc-us:PASS@res.proxshift.com:9000
export HTTPS_PROXY=http://USER-cc-us:PASS@res.proxshift.com:9000
export NO_PROXY=localhost,127.0.0.1

curl https://api.ipify.org
```


## Python

**requests**

```requests
import requests

proxy = "http://USER-cc-us:PASS@res.proxshift.com:9000"
session = requests.Session()
session.proxies = {"http": proxy, "https": proxy}

r = session.get("https://api.ipify.org", timeout=30)
print(r.text)

# 固定会话：按会话 ID 构建用户名
def proxy_for(sid: str, cc: str = "us", ttl: str = "10m") -> str:
    return f"http://USER-cc-{cc}-sid-{sid}-ttl-{ttl}:PASS@res.proxshift.com:9000"
```

**httpx**

```httpx
import httpx

proxy = "http://USER-cc-us:PASS@res.proxshift.com:9000"
with httpx.Client(proxy=proxy, timeout=30) as client:
    print(client.get("https://api.ipify.org").text)

# 异步
# async with httpx.AsyncClient(proxy=proxy) as client: ...
```

**aiohttp**

```aiohttp
import asyncio
import aiohttp

async def main():
    auth = aiohttp.BasicAuth("USER-cc-us", "PASS")
    async with aiohttp.ClientSession() as session:
        async with session.get("https://api.ipify.org",
                               proxy="http://res.proxshift.com:9000",
                               proxy_auth=auth, timeout=30) as r:
            print(await r.text())

asyncio.run(main())
```

**Scrapy**

```scrapy
import scrapy

class IpSpider(scrapy.Spider):
    name = "ip"

    def start_requests(self):
        # HttpProxyMiddleware（默认启用）从 URL 读取凭据
        yield scrapy.Request(
            "https://api.ipify.org",
            meta={"proxy": "http://USER-cc-us:PASS@res.proxshift.com:9000"},
        )

    def parse(self, response):
        yield {"ip": response.text}
```


## Node.js

**undici / fetch**

```undici
import { fetch, ProxyAgent } from "undici";

const dispatcher = new ProxyAgent("http://USER-cc-us:PASS@res.proxshift.com:9000");
const res = await fetch("https://api.ipify.org", { dispatcher });
console.log(await res.text());
```

**axios**

```axios
import axios from "axios";
import { HttpsProxyAgent } from "https-proxy-agent";

const agent = new HttpsProxyAgent("http://USER-cc-us:PASS@res.proxshift.com:9000");
const { data } = await axios.get("https://api.ipify.org", {
  httpsAgent: agent,
  proxy: false, // 交由代理处理
});
console.log(data);
```

**Playwright**

```playwright
import { chromium } from "playwright";

const browser = await chromium.launch({
  proxy: {
    server: "http://res.proxshift.com:9000",
    username: "USER-cc-us-sid-a1b2c3-ttl-30m",
    password: "PASS",
  },
});
const page = await browser.newPage();
await page.goto("https://api.ipify.org");
console.log(await page.textContent("body"));
await browser.close();
```

**Puppeteer**

```puppeteer
import puppeteer from "puppeteer";

const browser = await puppeteer.launch({
  args: ["--proxy-server=res.proxshift.com:9000"],
});
const page = await browser.newPage();
await page.authenticate({ username: "USER-cc-us-sid-a1b2c3", password: "PASS" });
await page.goto("https://api.ipify.org");
console.log(await page.evaluate(() => document.body.innerText));
await browser.close();
```


## PHP

**cURL**

```curl
$ch = curl_init("https://api.ipify.org");
curl_setopt_array($ch, [
    CURLOPT_PROXY          => "http://res.proxshift.com:9000",
    CURLOPT_PROXYUSERPWD   => "USER-cc-us:PASS",
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_TIMEOUT        => 30,
]);
echo curl_exec($ch);
```

**Guzzle**

```guzzle
$client = new \GuzzleHttp\Client();
$response = $client->get('https://api.ipify.org', [
    'proxy'   => 'http://USER-cc-us:PASS@res.proxshift.com:9000',
    'timeout' => 30,
]);
echo $response->getBody();
```


## Go、Java 和 C#

**Go**

```go
package main

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

func main() {
    proxyURL, _ := url.Parse("http://USER-cc-us:PASS@res.proxshift.com:9000")
    client := &http.Client{Transport: &http.Transport{Proxy: http.ProxyURL(proxyURL)}}
    resp, err := client.Get("https://api.ipify.org")
    if err != nil {
        panic(err)
    }
    defer resp.Body.Close()
    body, _ := io.ReadAll(resp.Body)
    fmt.Println(string(body))
}
```

**Java (OkHttp)**

```java
import okhttp3.*;
import java.net.InetSocketAddress;
import java.net.Proxy;

Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("res.proxshift.com", 9000));
OkHttpClient client = new OkHttpClient.Builder()
    .proxy(proxy)
    .proxyAuthenticator((route, response) -> response.request().newBuilder()
        .header("Proxy-Authorization", Credentials.basic("USER-cc-us", "PASS"))
        .build())
    .build();

try (Response res = client.newCall(new Request.Builder().url("https://api.ipify.org").build()).execute()) {
    System.out.println(res.body().string());
}

// 自 Java 8u111 起，java.net.http.HttpClient 默认禁用 CONNECT 的 Basic 身份验证。
// 使用 -Djdk.http.auth.tunneling.disabledSchemes= 启动 JVM 即可启用。
```

**C#**

```csharp
using System.Net;

var handler = new HttpClientHandler
{
    Proxy = new WebProxy("http://res.proxshift.com:9000")
    {
        Credentials = new NetworkCredential("USER-cc-us", "PASS")
    },
    UseProxy = true,
};
using var http = new HttpClient(handler);
Console.WriteLine(await http.GetStringAsync("https://api.ipify.org"));
```


## 浏览器和防关联工具

- Chrome 的 `--proxy-server` 参数不接受凭据。请使用 Playwright 或 Puppeteer（它们会替你响应身份验证质询），或将该设备加入[白名单](https://proxshift.com/zh/docs/authentication#ip-whitelist)，然后单独使用此参数。
- Selenium 同样没有内置代理身份验证；使用白名单最为可靠。
- 防关联浏览器（如 Multilogin、GoLogin、AdsPower、Dolphin）支持为每个配置文件输入一行 `host:port:user:pass`。粘贴专用地址行，或使用网关并为每个配置文件设置唯一的 `-sid-`。
- 手动配置时，Firefox 和 Chrome 会在每次会话中询问一次代理密码；自动化流程不应依赖此提示框。

> Tip：无论使用哪种客户端，都应先通过 `https://api.ipify.org` 测试，并与直连请求比较。如果两者输出相同的 IP，说明代理未被使用：请检查环境变量、`NO_PROXY`，以及所用库要求的是 `proxy` 还是 `proxies`。


来源：https://proxshift.com/zh/docs/examples
