# 会话控制

会话控制类型包含轮换会话和粘性会话两种

### **轮转会话**

当会话类型设为 **轮转会话** 时：

**动态IP分配**：每次请求自动分配**全新住宅IP**

**适用场景**：高匿名性业务需求

**配置规则**：

* 无需拼接会话标识参数
* 在端点生成器中启用 **轮转模式** 即可实时生效

{% hint style="success" %}
[**点击此处**](https://doc.thordata.com/doc/zh/proxies/residential-proxies/location-settings/region-entry) 查看轮换会话-白名单国家地区节点入口
{% endhint %}

### **粘性会话**

粘性会话允许保留单个 IP 地址，以便发起多个请求。要多次重复使用同一个 IP 地址，选择以下任一方式：

* **端点生成器配置**

▸ 切换会话模式为 黏性会话

▸ 设定持续时长（单位：分钟）

* **参数化配置**

在用户名后拼接：**`sessid-[自定义会话ID]+sesstime-[持续时间]`**

▸ 会话ID：字母数字组合（如abc123）

▸ 持续时间：整数分钟值（如10）

例如设定黏性模式持续时间为10分钟：`sessid-abc123-sesstime-10`

<figure><img src="https://4104892590-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FjqnwIl63IM96hzuNICho%2Fuploads%2FdlHsaRF7WAgl3z9MKaBA%2Fscreenshot_2025-08-01_14-39-53.gif?alt=media&#x26;token=38b01ec4-a7b0-4a68-b05c-5ac882599878" alt=""><figcaption></figcaption></figure>

新的 IP 地址。标准会话时间为 10 分钟或不超过 60 秒的不活动时间（无请求）之后，将自动分配一个新的 IP 地址。

> 例如您使用 `sessid-a123123+sesstime-10` 被分配至代理 IP `1.1.1.1` 后，只要持续使用该会话参数发送请求且代理节点保持可用状态，您的请求将始终通过 `1.1.1.1` 进行传输。当会话时间超过预设的 10 分钟时，下一个使用 `sessid-a123123+sesstime-10` 的请求将自动分配新代理 IP，例如 `1.1.1.2`。

您也可以设定多条不同的会话代理地址，比如：

```
user-USERNAME-sessid-a234234-sesstime-15:PASSWORD
user-USERNAME-sessid-a345345-sesstime-30:PASSWORD
user-USERNAME-sessid-a456456-sesstime-45:PASSWORD
user-USERNAME-sessid-a567567-sesstime-90:PASSWORD
```

**代码示例：**

`sessid-a123123-sesstime-10`在此示例中，演示了如何通过包含`sessid`字符串和`sesstime`（10分钟）参数的美国IP进行首次请求。在10分钟会话有效期内，所有后续查询将继续使用该美国IP地址。

{% tabs %}
{% tab title="cURL" %}

```sh
curl -x "https://td-customer-USERNAME-country-us-sessid-a123123-sesstime-10:PASSWORD@t.na.thordata.net:9999" "https://ipinfo.thordata.com"
```

{% endtab %}

{% tab title="C#" %}

```csharp
using System;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;

class csharp_https
{
    static void Main(string[] args)
    {
        Task t = new Task(DownloadPageAsync);
        t.Start();
        Console.ReadLine();
    }

    static async void DownloadPageAsync()
    {
        string page = "https://ipinfo.thordata.com";

        var proxy = new WebProxy("https://t.na.thordata.net:9999")
        {
            UseDefaultCredentials = false,
            Credentials = new NetworkCredential(
                userName: "td-customer-USERNAME-country-us-sessid-a123123-sesstime-10",
                password: "PASSWORD")
        };

        var httpClientHandler = new HttpClientHandler()
        {
            Proxy = proxy,
            ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator
        };

        var client = new HttpClient(handler: httpClientHandler, disposeHandler: true);
        var response = await client.GetAsync(page);

        using (HttpContent content = response.Content)
        {
            string result = await content.ReadAsStringAsync();
            Console.WriteLine(result);
            Console.WriteLine("Press any key to exit.");
            Console.ReadKey();
        }
    }
}
```

{% endtab %}

{% tab title="GO" %}

```go
package main

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

const (
	resourceUrl = "https://ipinfo.thordata.com"
	proxyHost   = "t.na.thordata.net:9999"
	username    = "td-customer-USERNAME-country-us-sessid-a123123-sesstime-10"
	password    = "PASSWORD"
)

func main() {
	proxyUrl := &url.URL{
		Scheme: "https",
		User:   url.UserPassword(username, password),
		Host:   proxyHost,
	}

	client := http.Client{
		Transport: &http.Transport{
			Proxy: http.ProxyURL(proxyUrl),
		},
	}

	resp, err := client.Get(resourceUrl)
	if err != nil {
		log.Fatal(err)
	}
	defer resp.Body.Close()

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		log.Fatal(err)
	}

	bodyString := string(body)
	fmt.Println(bodyString)
}
```

{% endtab %}

{% tab title="Java" %}

```java
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.BasicHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

public class JavaHttps {
    public static final String username = "td-customer-USERNAME-country-us-sessid-a123123-sesstime-10";
    public static final String password = "PASSWORD";
    public static final int port = 9999;
    public static final String proxyHost = "t.na.thordata.net";
    public CloseableHttpClient client;

    public JavaHttps() {
        HttpHost proxy = new HttpHost(proxyHost, port, "https");
        CredentialsProvider cred_provider = new BasicCredentialsProvider();
        cred_provider.setCredentials(new AuthScope(proxy),
                new UsernamePasswordCredentials(username, password));
        client = HttpClients.custom()
                .setConnectionManager(new BasicHttpClientConnectionManager())
                .setProxy(proxy)
                .setDefaultCredentialsProvider(cred_provider)
                .build();
    }

    public String request(String url) throws IOException {
        HttpGet request = new HttpGet(url);
        CloseableHttpResponse response = client.execute(request);
        try {
            return EntityUtils.toString(response.getEntity());
        } finally { response.close(); }
    }

    public void close() throws IOException { client.close(); }

    public static void main(String[] args) throws IOException {
        JavaHttps client = new JavaHttps();
        try {
            System.out.println(client.request("https://ipinfo.thordata.com"));
        } finally { client.close(); }
    }
}

```

{% endtab %}

{% tab title="PHP" %}

```php
<?php
  $url = 'https://ipinfo.thordata.com';
  $proxy = 't.na.thordata.net';
  $port = 9999;
  $user = 'td-customer-USERNAME-country-us-sessid-a123123-sesstime-10';
  $psw = 'PASSWORD';

  $ch = curl_init($url);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

  curl_setopt($ch, CURLOPT_PROXY, "$proxy:$port");
  curl_setopt($ch, CURLOPT_PROXYUSERPWD, "$user:$psw");
  $result = curl_exec($ch);
  curl_close($ch);

  if ($result)
  {
      echo $result . PHP_EOL;
  }
?>
```

{% endtab %}

{% tab title="Python" %}

```python
import requests

username = "td-customer-USERNAME-country-us-sessid-a123123-sesstime-10"
password = "PASSWORD"
proxy_server = "t.na.thordata.net:9999"

proxies = {"https": f"https://{username}:{password}@{proxy_server}"}

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

{% endtab %}

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

```
const rp = require('request-promise');

const username = "td-customer-USERNAME-country-us-sessid-a123123-sesstime-10";
const password = "PASSWORD";
const proxyServer = "t.na.thordata.net:9999";

rp({
    url: 'https://ipinfo.thordata.com',
    proxy: `https://${username}:${password}@${proxyServer}`,
})
.then(function(data) {
    console.log(data);
})
.catch(function(err) {
    console.error(err);
});
```

{% endtab %}

{% tab title="Untitled" %}

```ruby
require "uri"
require 'net/http'
require 'openssl'

proxy_host = 't.na.thordata.net'
proxy_port = 9999
proxy_user = 'td-customer-USERNAME-country-us-sessid-a123123-sesstime-10'
proxy_pass = 'PASSWORD'

uri = URI.parse('https://ipinfo.thordata.com')

proxy = Net::HTTP::Proxy(proxy_host, proxy_port, proxy_user, proxy_pass)

req = Net::HTTP::Get.new(uri)

result = proxy.start(uri.host, uri.port, use_ssl: true, ssl_version: :TLSv1_2) do |http|
  http.request(req)
end

puts result.body
```

{% endtab %}
{% endtabs %}

{% hint style="success" %}
[**点击此处**](https://doc.thordata.com/doc/zh/proxies/residential-proxies/location-settings/region-entry) 查看轮换会话-白名单国家地区节点入口
{% endhint %}
