在发送HTTP请求时,设置超时是一种常见的做法,以确保请求不会无限期地等待响应。以下是在不同编程语言中设置HTTP请求超时的方法:
Python
使用`requests`库发送HTTP请求时,可以通过`timeout`参数设置超时时间。
```python
import requests
url = 'http://example.com'
response = requests.get(url, timeout=5) 5秒超时
```
JavaScript (Node.js)
使用`http`或`https`模块发送请求时,可以通过`options`对象的`timeout`属性设置超时时间。
```javascript
const http = require('http');
const options = {
hostname: 'example.com',
port: 80,
path: '/',
timeout: 5000, // 5秒超时