> For the complete documentation index, see [llms.txt](https://docs.rapidproxy.io/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.rapidproxy.io/simplified-mandarin/dai-li/dai-ma-shi-li.md).

# 代码示例

本页面提供可在各种编程语言和工具中集成 Rapidproxy 代理的即用型**代码示例。您将找到**[**动态（轮换）住宅代理**](https://docs.rapidproxy.io/proxies/dynamic-residential-proxy)**、**[**静态住宅代理**](https://docs.rapidproxy.io/proxies/static-residential-proxy) **、无限量住宅代理**的示例用法，以及常用的身份验证方法。

***

### 1. 一般用法及如何解读这些示例 <a href="#id-1.-general-usage-and-how-to-read-these-examples" id="id-1.-general-usage-and-how-to-read-these-examples"></a>

Rapidproxy 支持多种代理身份验证方法，包括：

* [**用户名和密码验证**](https://docs.rapidproxy.io/proxies/dynamic-residential-proxy/get-proxy/user-and-pass-auth)— 每个子帐户的凭据
* [**IP 白名单**](https://docs.rapidproxy.io/proxies/dynamic-residential-proxy/get-proxy/api/ip-whitelisting)— 允许列入白名单的源 IP 身份验证

在适用的情况下，您会看到使用这两种方法的示例。

> 注意：请将占位符值（例如，，，`YOUR_PROXY_HOST`）替换为 Rapidproxy 控制面板中的实际值。`YOUR_PORTYOUR_USERNAMEYOUR_PASSWORD`

***

### 2. cURL 示例 <a href="#id-2.-curl-examples" id="id-2.-curl-examples"></a>

**动态住宅代理 — 用户名和密码**

```
curl -x http://YOUR_USERNAME:YOUR_PASSWORD@YOUR_PROXY_HOST:YOUR_PORT https://example.com
```

**动态住宅代理 — IP 白名单（无需凭证）**

```
curl -x http://YOUR_PROXY_HOST:YOUR_PORT https://example.com
```

*（请确保您的当前 IP 地址已列入白名单后再使用此请求。）*

**静态住宅代理**

```
curl -x http://YOUR_USERNAME:YOUR_PASSWORD@YOUR_STATIC_IP:YOUR_PORT https://example.com
```

**无限量住宅代理**&#x20;

```
curl -x "Servers" -U "Username_res_EU_sid_*******_time_10:Password"http://ipinfo.io
```

***

### 3. Python 示例（requests 库）

```
import requests

proxy = "http://YOUR_USERNAME:YOUR_PASSWORD@YOUR_PROXY_HOST:YOUR_PORT"

proxies = {
    "http": proxy,
    "https": proxy
}

url = "https://example.com"
response = requests.get(url, proxies=proxies)
print(response.text)
```

**仅限 IP 白名单**

```
import requests

proxy = "http://YOUR_PROXY_HOST:YOUR_PORT"

proxies = {
    "http": proxy,
    "https": proxy
}

response = requests.get("https://example.com", proxies=proxies)
print(response.text)
```

**无限量住宅代理**

```
import requests
if __name__ == '__main__':
proxyip = "http://USERNAME_res_EU_sid_*********_time_10:Password@Servers
url = "http://ipinfo.io"
proxies = {
'http': proxyip,
}
data = requests.get(url=url, proxies=proxies)
print(data.text)
```

***

### 4. Node.js 示例（axios） <a href="#id-4.-node.js-example-axios" id="id-4.-node.js-example-axios"></a>

**使用用户名和密码进行身份验证**

```
import axios from "axios";

const proxy = {
  host: "YOUR_PROXY_HOST",
  port: YOUR_PORT,
  auth: {
    username: "YOUR_USERNAME",
    password: "YOUR_PASSWORD"
  }
};

axios.get("https://example.com", { proxy })
  .then(res => console.log(res.data))
  .catch(err => console.error(err));
```

**仅限 IP 白名单**

```
import axios from "axios";

const proxy = {
  host: "YOUR_PROXY_HOST",
  port: YOUR_PORT
};

axios.get("https://example.com", { proxy })
  .then(res => console.log(res.data))
  .catch(err => console.error(err));
```

**无限量住宅代理**

```
import fetch from 'node-fetch';
import createHttpsProxyAgent from 'https-proxy-agent'

const username = 'Username_res_GLOBAL_sid_*********_time_10';
const password = 'Password';
const proxy = 'Server'

const agent = createHttpsProxyAgent(
http://`${username}:${password}@${proxy}`
);

const response = await fetch('http://ipinfo.io', {
  method: 'get',
  agent: agent,
});

console.log(await response.text());
```

***

### 5. Puppeteer 示例（无头浏览器） <a href="#id-5.-puppeteer-example-headless-browser" id="id-5.-puppeteer-example-headless-browser"></a>

**使用用户名和密码进行身份验证**

```
const puppeteer = require("puppeteer");

(async () => {
  const browser = await puppeteer.launch({
    args: [
      "--proxy-server=YOUR_PROXY_HOST:YOUR_PORT"
    ]
  });

  const page = await browser.newPage();
  await page.authenticate({
    username: "YOUR_USERNAME",
    password: "YOUR_PASSWORD"
  });

  await page.goto("https://example.com");
  console.log(await page.content());
  await browser.close();
})();
```

***

### 6. Java 示例（Apache HttpClient） <a href="#id-6.-java-example-apache-httpclient" id="id-6.-java-example-apache-httpclient"></a>

**使用用户名和密码进行身份验证**

```
HttpHost proxy = new HttpHost("YOUR_PROXY_HOST", YOUR_PORT);

CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(
    new AuthScope(proxy),
    new UsernamePasswordCredentials("YOUR_USERNAME", "YOUR_PASSWORD")
);

CloseableHttpClient client = HttpClients.custom()
    .setDefaultCredentialsProvider(credsProvider)
    .build();

HttpGet request = new HttpGet("https://example.com");
HttpResponse response = client.execute(proxy, request);

System.out.println(EntityUtils.toString(response.getEntity()));
```

**无限量住宅代理**

```
public class Main {
    public static void main(String[] args) throws Exception {
        try {
            String proxyHost = "Server";
            int proxyPort = ****;
            Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort));
            String username = "Username_res_GLOBAL_sid_********_time_10";
            String password = "Password";
            String credentials = username + ":" + password;
            URL url = new URL("http://ipinfo.io");
            HttpURLConnection connection = (HttpURLConnection) url.openConnection(proxy);
            connection.setRequestMethod("GET");
            connection.setRequestProperty("Proxy-Authorization", "Basic " + Base64.getEncoder().encodeToString(credentials.getBytes()));
            int responseCode = connection.getResponseCode();
            System.out.println("Response Code: " + responseCode);
            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String inputLine;
            StringBuilder response = new StringBuilder();
            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();
            System.out.println((response.toString()));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
```

***

### 7. 无限量住宅代理其余代码示例 <a href="#id-7.-tips-for-using-proxies-in-code" id="id-7.-tips-for-using-proxies-in-code"></a>

**PHP**

```
$ch = curl_init();
curl_setopt($ch, CURLOPT_PROXY, "Serve" );
curl_setopt($ch, CURLOPT_PROXYUSERPWD, "Username_res_GLOBAL_sid_********_time_10:Password");
curl_setopt($ch, CURLOPT_PROXYTYPE, CURLPROXY_HTTP);
curl_setopt($ch, CURLOPT_URL, 'http://ipinfo.io');
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
$result = curl_exec($ch);
curl_close($ch);
echo $result;
```

**GO**

```
package main
import (
	"fmt"
	"io/ioutil"
	"net/http"
	"net/url"
	"os"
)
func main() {
	proxyURL, _ := url.Parse(" http://Username_res_GLOBAL_sid_********_time_10:Password@Server)
	proxy := http.ProxyURL(proxyURL)
	transport := &http.Transport{
		Proxy: proxy,
	}
	client := &http.Client{
		Transport: transport,
	}
	targetURL := "http://ipinfo.io"

	resp, err := client.Get(targetURL)
	if err != nil {
		fmt.Fprintln(os.Stderr, "Error fetching from", targetURL, ":", err)
		os.Exit(1)
	}
	defer resp.Body.Close()

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		fmt.Fprintln(os.Stderr, "Error reading response body:", err)
		os.Exit(1)
	}

	fmt.Println(string(body))
}
```

**C#**

```
// See https://aka.ms/new-console-template for more information
using System.Net;
using System.Threading;

var handler = new HttpClientHandler
{
    UseProxy = true
};
var proxy = new WebProxy("http://Server");
var proxyUsername = "Username_res_GLOBAL_sid_********_time_10";
var proxyPass = "Password";
proxy.Credentials = new NetworkCredential(proxyUsername, proxyPass);
handler.Proxy = proxy;
var httpClient = new HttpClient(handler);

httpClient.Timeout = TimeSpan.FromSeconds(15);

var task = httpClient.GetStringAsync("http://ipinfo.io/json");
task.Wait();
Console.WriteLine(task.Result);
```

### 8. 在代码中使用代理的技巧 <a href="#id-7.-tips-for-using-proxies-in-code" id="id-7.-tips-for-using-proxies-in-code"></a>

**协议支持**

* HTTP 和 HTTPS 均受支持
* 如果您的客户端支持 SOCKS5 协议，则可以使用该协议。

**粘性会话（动态代理）**

如果在生成代理凭据时配置了**粘性会话：**

* 会话内的每个请求都将使用**相同的IP地址**
* 适用于登录、表单提交和基于会话的自动化

**IP 白名单**

如果使用 IP 白名单：

* 确认您的应用程序或服务器的源 IP 地址已添加到白名单中。
* 来自非白名单 IP 的请求将被阻止。

***

### 9. 故障排除 <a href="#id-8.-troubleshooting" id="id-8.-troubleshooting"></a>

如果您的代码收到代理错误：

* 仔细检查代理主机/端口值
* 请确保凭据正确（用于用户名/密码验证）。
* 请确认您的IP地址已加入白名单（如适用）。
* 请检查您的工具/客户端是否支持您正在使用的代理协议。

如果问题仍然存在，请联系技术支持：

* **Rapidproxy 网站上的在线实时聊天**
* **电子邮件：** `support@rapidproxy.io`

***

### 10. 安全须知 <a href="#id-9.-security-notes" id="id-9.-security-notes"></a>

* 切勿公开分享凭证
* 将代理用户名和密码存储在安全的配置或环境变量中。
* 如果凭证泄露，请轮换使用。

[<br>](https://docs.rapidproxy.io/proxies/static-residential-proxy/get-static-proxy-ip)
