You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用PHP的Curl发送指定POST请求并替换请求体code值

使用PHP cURL发送指定POST请求的实现

以下是把你提供的HTTP请求转换成PHP cURL代码的实现,其中请求体里的herecode可以通过变量轻松替换:

<?php
// 目标请求地址
$targetUrl = 'https://exemple.com/account/p_api/v1/account/authorization/assign';
// 替换原请求中的herecode,改成你需要的代码
$customCode = 'your-custom-code';

// 构造JSON格式的请求体
$postData = json_encode([
    'code' => $customCode
]);

// 初始化cURL会话
$ch = curl_init($targetUrl);

// 设置POST请求相关选项
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);

// 设置请求头,完全对应原请求的头部信息
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Host: exemple.com',
    'Cookie: exemle-locale=en;',
    'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:107.0) Gecko/20100101 Firefox/107.0',
    'Accept: */*',
    'Accept-Language: en-US,en;q=0.5',
    'Accept-Encoding: gzip, deflate',
    'Content-Type: application/json',
    'Origin: https://exemple.com',
    'Sec-Fetch-Dest: empty',
    'Sec-Fetch-Mode: cors',
    'Sec-Fetch-Site: same-origin',
    'Te: trailers',
    'Connection: close'
]);

// 配置响应处理:返回内容而非直接输出,自动处理gzip压缩
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_ENCODING, 'gzip, deflate');

// 执行请求并获取响应
$response = curl_exec($ch);
$httpStatusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

// 检查请求是否出错
if (curl_errno($ch)) {
    echo 'cURL执行错误:' . curl_error($ch);
} else {
    // 输出结果,可根据需求调整处理逻辑
    echo 'HTTP状态码:' . $httpStatusCode . PHP_EOL;
    echo '服务器响应:' . $response;
}

// 关闭cURL会话
curl_close($ch);
?>

关键说明

  • 替换代码只需修改$customCode变量的值即可,无需改动请求体结构
  • Content-Length无需手动设置,cURL会自动计算并添加到请求头中
  • 开启CURLOPT_ENCODING是为了匹配原请求的Accept-Encoding头部,自动处理服务器返回的压缩响应
  • 如果需要维持会话(比如后续请求复用Cookie),可以添加CURLOPT_COOKIEJAR和CURLOPT_COOKIEFILE选项来保存/读取Cookie文件

内容的提问来源于stack exchange,提问作者Tashya Walton

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 03:05:39