这段python 如何转成 PHP的请求


user_payload = {
    "header": {
        "authorityType": 5,
        "userName": "3123",
       
    },
    "body": {
        "solutionType": "phone",
        "startDate": "2023-02-18 00:00:00",
        "endDate": "2023-02-18 23:59:59",
     
    }
} 
http_headers = {
    "Accept-Encoding": "gzip, deflate",
    "Content-Type": "application/json",
    "Accept": "application/json"
}
user_payload = json.dumps(user_payload)
response = requests.request("POST", url, data=user_payload, headers=http_headers)
print(response.text)

这段python 如何转成 PHP的请求

下面是将这段 Python 代码转化为 PHP 请求的示例代码:

<?php

$url = 'http://example.com'; // 请求的 URL
$data = array(
    'header' => array(
        'authorityType' => 5,
        'userName' => '3123'
    ),
    'body' => array(
        'solutionType' => 'phone',
        'startDate' => '2023-02-18 00:00:00',
        'endDate' => '2023-02-18 23:59:59'
    )
);
$options = array(
    'http' => array(
        'header'  => "Content-type: application/json\r\nAccept: application/json\r\n",
        'method'  => 'POST',
        'content' => json_encode($data),
    ),
);

$context  = stream_context_create($options);
$response = file_get_contents($url, false, $context);
echo $response;

?>

在 PHP 中,我们可以使用 file_get_contents() 函数来发送 HTTP 请求。我们可以使用 stream_context_create() 函数创建一个包含请求参数的上下文,然后将其传递给 file_get_contents() 函数。

在这个例子中,我们使用 json_encode() 函数将请求体转化为 JSON 格式。同时,在请求头中指定了内容类型为 application/json,以及接受的内容类型也是 application/json。

转换如下:

$url = '你的路径'
$user_payload = [
  "header" => [
     "authorityType"  =>  5,
    "userName" => "3123"
  ],
  "body" => [
    "solutionType"  =>  "phone",
    "startDate" => "2023-02-18 00:00:00",
    "endDate" =>  "2023-02-18 23:59:59"
  ]
];
$http_header = [
  "Accept-Encoding"  =>  "gzip, deflate",
  "Content-Type" => "application/json",
  "Accept" =>  "application/json"
];

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);  // 对认证证书来源的检查   // https请求 不验证证书和hosts
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);  // 从证书中检查SSL加密算法是否存在
curl_setopt($ch, CURLOPT_POST, true); // 发送一个常规的Post请求
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($user_payload));     // Post提交的数据包
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);     // 获取的信息以文件流的形式返回 
curl_setopt($ch, CURLOPT_HTTPHEADER, $http_header ); //模拟的header头
$response = curl_exec($ch);
curl_close($ch);
// 获取的结果
return $response;

不知道你这个问题是否已经解决, 如果还没有解决的话:

如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 写成博客, 将相关链接放在评论区, 以帮助更多的人 ^-^