> For the complete documentation index, see [llms.txt](https://developers.oxylabs.io/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://developers.oxylabs.io/products/cn/dai-li/mobile-proxies/session-control.md).

# 会话控制

### 建立会话

会话 ID 参数允许你保持相同的 IP 地址来执行多个请求。若要多次重用同一 IP，请在 `sessid` 参数后使用 `用户名` 并使用随机创建的字母数字字符串，例如， `sessid-abcd1234`.

{% embed url="<https://files.gitbook.com/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FzrXw45naRpCZ0Ku9AjY1%2Fuploads%2FxR5NdybM3rjlbhAbPBZN%2Fsession-id.mp4?alt=media>" %}

标准会话时长为 10 分钟，或最多 60 秒无活动（无请求）。之后会自动分配新的 IP 地址。要调整所需的会话时长，请参阅 [**会话时间**](/products/cn/dai-li/mobile-proxies/session-control.md#session-time) 部分。

例如，你的初始查询使用 `sessid-abcd1234` 分配的代理 IP 地址 `1.1.1.1`。只要你继续使用相同的会话 ID 发送新请求，并且该 IP 地址保持在线且可用，系统就会通过该 IP 路由你的查询 `1.1.1.1`。如果你停止发送请求 60 秒，或者该 IP 地址不再在线，系统将分配一个新的代理 IP。你下一次使用 `sessid-abcd1234` 将通过不同的 IP 地址路由，例如 `1.1.1.2`.

#### **凭证列表示例：**

示例表示建立不同会话的一组凭证。

```
customer-USERNAME-sessid-iqwcp:PASSWORD
customer-USERNAME-sessid-tevab:PASSWORD
customer-USERNAME-sessid-6drwn:PASSWORD
customer-USERNAME-sessid-7eh7g:PASSWORD
customer-USERNAME-sessid-z7cao:PASSWORD
```

#### 代码示例

在此示例中，我们使用的是德国 IP，并配合 `sessid-abcd1234` 的用户名中使用德国 IP 进行首次请求。之后所有请求都将继续使用相同的德国 IP：

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

```shell
curl -x pr.oxylabs.io:7777 -U "customer-USERNAME-cc-DE-sessid-abcd1234:PASSWORD" https://ip.oxylabs.io/location
```

{% endtab %}

{% tab title="PHP" %}

```php
<?php
$username = 'USERNAME';
$password = 'PASSWORD';
$country = 'DE';
$session = mt_rand();
$proxy = 'pr.oxylabs.io:7777';
$query = curl_init('https://ip.oxylabs.io/location');
curl_setopt($query, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($query, CURLOPT_PROXY, "http://$proxy");
curl_setopt($query, CURLOPT_PROXYUSERPWD, "customer-$username-cc-$country-sessid-$session:$password");
$output = curl_exec($query);
curl_close($query);
if ($output)
    echo $output;
?>
```

{% endtab %}

{% tab title="Python" %}

```python
import urllib.request
import random
username = 'USERNAME'
password = 'PASSWORD'
country = 'DE'
session = random.random()
entry = ('http://customer-%s-cc-%s-sessid-%s:%s@pr.oxylabs.io:7777' %
    (username, country, session, password))
query = urllib.request.ProxyHandler({
    'http': entry,
    'https': entry,
})
execute = urllib.request.build_opener(query)
print(execute.open('https://ip.oxylabs.io/location').read())
```

{% endtab %}

{% tab title="Java" %}

```java
package example;

import java.io.*;
import java.util.Random;
import org.apache.http.HttpHost;
import org.apache.http.auth.*;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.fluent.Request;
import org.apache.http.client.methods.*;
import org.apache.http.impl.client.*;
import org.apache.http.impl.conn.BasicHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;

class Client {
    public static final String username = "USERNAME";
    public static final String password = "PASSWORD";
    public String session_id = Integer.toString(new Random().nextInt(Integer.MAX_VALUE));
    public CloseableHttpClient client;

    public Client(String country) {
        String login = "customer-"+username+(country!=null ? "-cc-"+country : "")
            +"-sessid-" + session_id;
        HttpHost entry_node = new HttpHost("pr.oxylabs.io:7777");
        CredentialsProvider credentials_provider = new BasicCredentialsProvider();
        credentials_provider.setCredentials(new AuthScope(entry_node),
            new UsernamePasswordCredentials(login, password));
        client = HttpClients.custom()
            .setConnectionManager(new BasicHttpClientConnectionManager())
            .setProxy(entry_node)
            .setDefaultCredentialsProvider(credentials_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 class Example {
    public static void main(String[] args) throws IOException {
        Client client = new Client("de");
        try {
            System.out.println(client.request("https://ip.oxylabs.io/location"));
        } finally { client.close(); }
    }
}
```

{% endtab %}

{% tab title="C#" %}

```csharp
using System;
using System.Net;

class Client : WebClient
{
    public static string username = "USERNAME";
    public static string password = "PASSWORD";
    public string session_id = new Random().Next().ToString();

    public Client(string country_iso = null)
    {
        this.Proxy = new WebProxy("pr.oxylabs.io:7777");
        var login = "customer-"+username+(country_iso != null ? "-cc-"+country_iso : "")
            +"-sessid-"+session_id;
        this.Proxy.Credentials = new NetworkCredential(login, password);
    }

    protected override WebRequest GetWebRequest(Uri address)
    {
        var request = base.GetWebRequest(address) as HttpWebRequest;
        request.ConnectionGroupName = session_id;
        return request;
    }
}

class Example
{
    static void Main()
    {
        var client = new Client("de");
        Console.WriteLine(client.DownloadString("https://ip.oxylabs.io/location"));
    }
}
```

{% endtab %}

{% tab title="Ruby" %}

```ruby
require 'uri'
require 'net/http'
require 'net/https'

entry_node = 'pr.oxylabs.io'
entry_port = '7777'
username = 'USERNAME'
password = 'PASSWORD'
session_id = Random.rand(1000000)

uri = URI.parse("https://ip.oxylabs.io/location")
headers = {
    'Accept-Encoding' => 'gzip'
}

proxy = Net::HTTP::Proxy(entry_node, entry_port, "#{username}-cc-DE-sessid-#{session_id}", password)
http = proxy.new(uri.host,uri.port)

if uri.scheme == 'https'
    http.use_ssl = true
    http.verify_mode = OpenSSL::SSL::VERIFY_NONE
end

req = Net::HTTP::Get.new(uri.path, headers)

result = http.start do |con|
    con.request(req)
end

puts result.body
```

{% endtab %}
{% endtabs %}

### 会话时长

该 `sesstime` 参数与 `sessid`一起使用，并允许你将会话延长到 10 分钟以上或为其设置特定时间。

该 `sessid_oneip` 参数是 `sessid` 的替代方案，适用于你必须在整个会话期间保持完全相同 IP 的情况。

对于普通的 `sessid`，如果分配的出口节点在会话时间到期前离线，系统会自动分配一个新的 IP，你的会话将继续。使用 `sessid_oneip`，会话绑定到单个出口节点：一旦该 IP 不再可用，请求不会轮换到新的 IP，而是返回 HTTP `502` 响应失败。此时你应使用新的 `sessid_oneip` 值分隔。 `sessid_oneip` 可与 `sesstime` 以相同方式组合使用 `sessid`.

{% hint style="success" %}
你可以使用 `sesstime` 参数来 **保持相同 IP 最长 1440 分钟** （24 小时）。\
但是，由于移动代理池是动态的，你的连接可能会更早结束。如果发生这种情况，请使用新的会话参数开始一个会话。
{% endhint %}

{% hint style="warning" %}
会话时长参数并不保证所有查询都能在会话结束前完成。即使请求尚未完成，会话也会在设置的时间限制内过期。

`sessid_oneip` 是 `sessid`的可选替代方案。默认的 `sessid` 行为（当出口节点过期时自动轮换到新 IP）保持不变。
{% endhint %}

#### **凭证列表示例：**

示例表示一组建立不同会话、具有不同会话时长（分钟）的凭证。

```
customer-USERNAME-sessid-iqwcp-sesstime-5:PASSWORD
customer-USERNAME-sessid-tevab-sesstime-12:PASSWORD
customer-USERNAME-sessid-6drwn-sesstime-30:PASSWORD
customer-USERNAME-sessid-7eh7g-sesstime-60:PASSWORD
customer-USERNAME-sessid-z7cao-sesstime-1440:PASSWORD
```

#### 代码示例

我们选择了与前一个示例相同的德国 IP，这次我们添加 `sessid`字符串和 `sesstime` 参数，时长为 7 分钟：

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

```shell
curl -x pr.oxylabs.io:7777 -U "customer-USERNAME-cc-DE-sessid-abcd1234-sesstime-7:PASSWORD" https://ip.oxylabs.io/location
```

{% endtab %}

{% tab title="PHP" %}

```php
<?php
$username = 'USERNAME';
$password = 'PASSWORD';
$country = 'DE';
$session = mt_rand();
$sesstime = 7;
$proxy = 'pr.oxylabs.io:7777';
$query = curl_init('https://ip.oxylabs.io/location');
curl_setopt($query, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($query, CURLOPT_PROXY, "http://$proxy");
curl_setopt($query, CURLOPT_PROXYUSERPWD, "customer-$username-cc-$country-sessid-$session-sesstime-$sesstime:$password");
$output = curl_exec($query);
curl_close($query);
if ($output)
    echo $output;
?>
```

{% endtab %}

{% tab title="Python" %}

```python
import urllib.request
import random
username = 'USERNAME'
password = 'PASSWORD'
country = 'DE'
session = random.random()
sesstime = 7
entry = ('http://customer-%s-cc-%s-sessid-%s-sesstime-%d:%s@pr.oxylabs.io:7777' %
    (username, country, city, session, sesstime, password))
query = urllib.request.ProxyHandler({
    'http': entry,
    'https': entry,
})
execute = urllib.request.build_opener(query)
print(execute.open('https://ip.oxylabs.io/location').read())
```

{% endtab %}

{% tab title="Java" %}

```java
package example;

import java.io.*;
import java.util.Random;
import org.apache.http.HttpHost;
import org.apache.http.auth.*;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.fluent.Request;
import org.apache.http.client.methods.*;
import org.apache.http.impl.client.*;
import org.apache.http.impl.conn.BasicHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;

class Client {
    public static final String username = "USERNAME";
    public static final String password = "PASSWORD";
    public String session_id = Integer.toString(new Random().nextInt(Integer.MAX_VALUE));
    public String sesstime = "7";
    public CloseableHttpClient client;

    public Client(String country) {
        String login = "customer-"+username+(country_iso != null ? "-cc-"+country_iso : "")+"-sessid-"+session_id+"-sesstime-" +sesstime;
        HttpHost entry_node = new HttpHost("pr.oxylabs.io:7777");
        CredentialsProvider credentials_provider = new BasicCredentialsProvider();
        credentials_provider.setCredentials(new AuthScope(entry_node),
            new UsernamePasswordCredentials(login, password));
        client = HttpClients.custom()
            .setConnectionManager(new BasicHttpClientConnectionManager())
            .setProxy(entry_node)
            .setDefaultCredentialsProvider(credentials_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 class Example {
    public static void main(String[] args) throws IOException {
        Client client = new Client("de");
        try {
            System.out.println(client.request("https://ip.oxylabs.io/location"));
        } finally { client.close(); }
    }
}
```

{% endtab %}

{% tab title="C#" %}

```csharp
using System;
using System.Net;

class Client : WebClient
{
    public static string username = "USERNAME";
    public static string password = "PASSWORD";
    public string session_id = new Random().Next().ToString();

    public Client(string country_iso = null)
    {
        this.Proxy = new WebProxy("pr.oxylabs.io:7777");
        var login = "customer-"+username+(country_iso != null ? "-cc-"+country_iso : "")
            +"-sessid-"+session_id;
        this.Proxy.Credentials = new NetworkCredential(login, password);
    }

    protected override WebRequest GetWebRequest(Uri address)
    {
        var request = base.GetWebRequest(address) as HttpWebRequest;
        request.ConnectionGroupName = session_id;
        return request;
    }
}

class Example
{
    static void Main()
    {
        var client = new Client("de");
        Console.WriteLine(client.DownloadString("https://ip.oxylabs.io/location"));
    }
}
```

{% endtab %}

{% tab title="Ruby" %}

```ruby
require 'uri'
require 'net/http'
require 'net/https'

entry_node = 'pr.oxylabs.io'
entry_port = '7777'
username = 'USERNAME'
password = 'PASSWORD'
session_id = Random.rand(1000000)
sesstime = 7

uri = URI.parse("https://ip.oxylabs.io/location")
headers = {
    'Accept-Encoding' => 'gzip'
}

proxy = Net::HTTP::Proxy(entry_node, entry_port, "#{username}-cc-DE-sessid-#{session_id}-sesstime-#{sesstime}", password)
http = proxy.new(uri.host,uri.port)

if uri.scheme == 'https'
    http.use_ssl = true
    http.verify_mode = OpenSSL::SSL::VERIFY_NONE
end

req = Net::HTTP::Get.new(uri.path, headers)

result = http.start do |con|
    con.request(req)
end

puts result.body
```

{% endtab %}
{% endtabs %}

要设置粘性代理入口节点，请了解更多 [**此处**](/products/cn/dai-li/mobile-proxies/session-control/sticky-proxy-entry-nodes.md).


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://developers.oxylabs.io/products/cn/dai-li/mobile-proxies/session-control.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
