0
# HTTP Infrastructure
1
2
Comprehensive HTTP client implementation with connection pooling, proxy support, pre-connected pools for performance optimization, and custom certificate handling. Supports both HTTP and HTTPS with configurable timeouts, keep-alive connections, and advanced connection management features.
3
4
## Capabilities
5
6
### API Request Handler
7
8
Main HTTP request handler with connection pooling, proxy support, and configurable timeouts.
9
10
```python { .api }
11
class ApiRequest:
12
def __init__(self, host: str, req_timeout: int = 60, debug: bool = False,
13
proxy: str = None, is_http: bool = False, certification = None,
14
pre_conn_pool_size: int = 0):
15
"""
16
Create API request handler.
17
18
Args:
19
host (str): Target host for requests
20
req_timeout (int): Request timeout in seconds (default: 60)
21
debug (bool): Enable debug logging (default: False)
22
proxy (str, optional): Proxy URL
23
is_http (bool): Use HTTP instead of HTTPS (default: False)
24
certification: Certificate path or False to disable verification
25
pre_conn_pool_size (int): Pre-connected pool size (default: 0)
26
"""
27
28
def set_req_timeout(self, req_timeout: int) -> None:
29
"""
30
Set request timeout.
31
32
Args:
33
req_timeout (int): Timeout in seconds
34
"""
35
36
def is_keep_alive(self) -> bool:
37
"""
38
Check if keep-alive is enabled.
39
40
Returns:
41
bool: True if keep-alive is enabled
42
"""
43
44
def set_keep_alive(self, flag: bool = True) -> None:
45
"""
46
Enable or disable keep-alive connections.
47
48
Args:
49
flag (bool): Enable keep-alive (default: True)
50
"""
51
52
def set_debug(self, debug: bool) -> None:
53
"""
54
Enable or disable debug logging.
55
56
Args:
57
debug (bool): Enable debug logging
58
"""
59
60
def send_request(self, req_inter: RequestInternal):
61
"""
62
Send HTTP request.
63
64
Args:
65
req_inter (RequestInternal): Request object
66
67
Returns:
68
Response: HTTP response object
69
70
Raises:
71
TencentCloudSDKException: On network errors or invalid methods
72
"""
73
```
74
75
### Proxy Connection Management
76
77
HTTP connection management with proxy support and certificate handling.
78
79
```python { .api }
80
class ProxyConnection:
81
def __init__(self, host: str, timeout: int = 60, proxy: str = None,
82
certification = None, is_http: bool = False,
83
pre_conn_pool_size: int = 0):
84
"""
85
Create proxy connection handler.
86
87
Args:
88
host (str): Target host
89
timeout (int): Connection timeout (default: 60)
90
proxy (str, optional): Proxy URL
91
certification: Certificate path or None for default
92
is_http (bool): Use HTTP instead of HTTPS (default: False)
93
pre_conn_pool_size (int): Pre-connected pool size (default: 0)
94
"""
95
96
def request(self, method: str, url: str, body = None, headers: dict = None):
97
"""
98
Make HTTP request.
99
100
Args:
101
method (str): HTTP method (GET, POST, etc.)
102
url (str): Request URL
103
body: Request body
104
headers (dict, optional): Request headers
105
106
Returns:
107
Response: HTTP response object
108
"""
109
```
110
111
### Request Internal Representation
112
113
Internal request object for building HTTP requests.
114
115
```python { .api }
116
class RequestInternal:
117
def __init__(self, host: str = "", method: str = "", uri: str = "",
118
header: dict = None, data: str = ""):
119
"""
120
Create internal request representation.
121
122
Args:
123
host (str): Target host
124
method (str): HTTP method
125
uri (str): Request URI
126
header (dict, optional): Request headers
127
data (str): Request body data
128
"""
129
```
130
131
### Response Formatting
132
133
HTTP response formatting utility for logging and debugging.
134
135
```python { .api }
136
class ResponsePrettyFormatter:
137
def __init__(self, resp, format_body: bool = True, delimiter: str = "\n"):
138
"""
139
Create response formatter.
140
141
Args:
142
resp: HTTP response object
143
format_body (bool): Include response body (default: True)
144
delimiter (str): Line delimiter (default: "\n")
145
"""
146
147
@staticmethod
148
def str_ver(ver: int) -> str:
149
"""
150
Convert HTTP version number to string.
151
152
Args:
153
ver (int): HTTP version number (10, 11, 20)
154
155
Returns:
156
str: HTTP version string ("HTTP/1.0", "HTTP/1.1", "HTTP/2.0")
157
"""
158
```
159
160
### Pre-Connected Connection Pools
161
162
Advanced connection pooling with pre-connected connections for improved performance.
163
164
```python { .api }
165
class HTTPSPreConnPool:
166
def __init__(self, *args, **kwargs):
167
"""
168
HTTPS connection pool with pre-connected connections.
169
170
Automatically maintains a pool of pre-connected HTTPS connections
171
for improved performance by reducing connection establishment overhead.
172
"""
173
174
class HTTPPreConnPool:
175
def __init__(self, *args, **kwargs):
176
"""
177
HTTP connection pool with pre-connected connections.
178
179
Automatically maintains a pool of pre-connected HTTP connections
180
for improved performance by reducing connection establishment overhead.
181
"""
182
183
class PreConnPoolManager:
184
def __init__(self, pool_size: int, *args, **kwargs):
185
"""
186
Pool manager for pre-connected connection pools.
187
188
Args:
189
pool_size (int): Maximum number of connections per pool
190
"""
191
192
class PreConnAdapter:
193
def __init__(self, conn_pool_size: int, *args, **kwargs):
194
"""
195
HTTP adapter using pre-connected connection pools.
196
197
Args:
198
conn_pool_size (int): Connection pool size
199
"""
200
```
201
202
### Utility Functions
203
204
```python { .api }
205
def _get_proxy_from_env(host: str, varname: str = "HTTPS_PROXY") -> str:
206
"""
207
Extract proxy configuration from environment variables.
208
209
Args:
210
host (str): Target host to check against NO_PROXY
211
varname (str): Environment variable name (default: "HTTPS_PROXY")
212
213
Returns:
214
str or None: Proxy URL if found and not excluded, None otherwise
215
"""
216
```
217
218
## Usage Examples
219
220
### Basic HTTP Client
221
222
```python
223
from tencentcloud.common.http.request import ApiRequest, RequestInternal
224
225
# Create API request handler
226
request = ApiRequest("api.example.com", req_timeout=30)
227
228
# Create request object
229
req = RequestInternal(
230
host="api.example.com",
231
method="POST",
232
uri="/api/v1/endpoint",
233
header={"Content-Type": "application/json"},
234
data='{"key": "value"}'
235
)
236
237
# Send request
238
try:
239
response = request.send_request(req)
240
print(response.status_code)
241
print(response.text)
242
except Exception as e:
243
print(f"Request failed: {e}")
244
```
245
246
### HTTP Client with Proxy
247
248
```python
249
from tencentcloud.common.http.request import ApiRequest
250
251
# Create client with proxy
252
request = ApiRequest(
253
host="api.example.com",
254
proxy="http://proxy.example.com:8080",
255
req_timeout=60
256
)
257
258
# Enable keep-alive for better performance
259
request.set_keep_alive(True)
260
```
261
262
### Pre-Connected Connection Pools
263
264
```python
265
from tencentcloud.common.http.request import ApiRequest
266
267
# Create client with pre-connected pool for better performance
268
request = ApiRequest(
269
host="api.example.com",
270
pre_conn_pool_size=10 # Maintain 10 pre-connected connections
271
)
272
```
273
274
### HTTPS with Custom Certificates
275
276
```python
277
from tencentcloud.common.http.request import ApiRequest
278
279
# Use custom certificate bundle
280
request = ApiRequest(
281
host="api.example.com",
282
certification="/path/to/custom/ca-bundle.crt"
283
)
284
285
# Disable certificate verification (not recommended for production)
286
request = ApiRequest(
287
host="api.example.com",
288
certification=False
289
)
290
```
291
292
### Debug Logging
293
294
```python
295
from tencentcloud.common.http.request import ApiRequest
296
297
# Enable debug logging
298
request = ApiRequest("api.example.com", debug=True)
299
300
# Or enable after creation
301
request.set_debug(True)
302
```
303
304
### Environment-Based Proxy Configuration
305
306
```python
307
import os
308
from tencentcloud.common.http.request import _get_proxy_from_env
309
310
# Set proxy in environment
311
os.environ["HTTPS_PROXY"] = "http://proxy.example.com:8080"
312
os.environ["NO_PROXY"] = "localhost,127.0.0.1"
313
314
# Get proxy for host (respects NO_PROXY)
315
proxy = _get_proxy_from_env("api.example.com")
316
if proxy:
317
print(f"Using proxy: {proxy}")
318
```