如果输入的是POST呢,要兼容GET和POST
时间: 2024-03-20 20:39:47 浏览: 20
如果您想要兼容 GET 和 POST 请求,并且保持相同的 Python requests 格式,可以尝试使用以下 PHP 代码:
```php
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST') {
$request = $_POST['request'];
// 将请求包转换为 Python requests 格式
$python_code = 'import requests' . PHP_EOL;
$python_code .= 'url = "' . $request['url'] . '"' . PHP_EOL;
$python_code .= 'headers = {' . PHP_EOL;
foreach($request['headers'] as $header) {
$python_code .= ' "' . $header['name'] . '": "' . $header['value'] . '",' . PHP_EOL;
}
$python_code .= '}' . PHP_EOL;
if($request['method'] == 'GET') {
$python_code .= 'response = requests.get(url, headers=headers)' . PHP_EOL;
} else {
$python_code .= 'data = {' . PHP_EOL;
foreach($request['data'] as $data) {
$python_code .= ' "' . $data['name'] . '": "' . $data['value'] . '",' . PHP_EOL;
}
$python_code .= '}' . PHP_EOL;
$python_code .= 'response = requests.post(url, headers=headers, data=data)' . PHP_EOL;
}
$python_code .= 'print(response.content)' . PHP_EOL;
// 输出转换后的 Python 代码
echo '<pre>' . htmlspecialchars($python_code) . '</pre>';
}
?>
<form method="post">
<label>请求包:</label><br>
<textarea name="request" rows="10" cols="50"></textarea><br>
<input type="submit" value="提交">
</form>
```
这段代码与之前的代码类似,不同之处在于它通过判断请求方法来决定是使用 GET 还是 POST 方法发送请求,并且在 POST 请求中添加了一个 data 参数,用于传递请求体数据。同时,它保持了与之前相同的 Python requests 格式,将请求头和请求体数据都转换为 Python 字典格式。