如何从wp_remote_post请求中移除Content-Length请求头?
解决WordPress向Apps Script发送POST请求的400错误问题
首先修正请求体格式:你设置了Content-Type: application/json,但直接传数组作为body的话,WordPress会自动把它编码成表单数据(application/x-www-form-urlencoded),导致格式不匹配。先把数组转成JSON字符串:
$body = json_encode(array( 'firstName' => 'WhyWontYouWork' ));
接下来处理Content-Length头的问题——WordPress的WP_Http组件会自动计算并添加这个头,我们用过滤器在请求发送前移除它:
方法1:用自定义标记精准控制
在请求参数里加个自定义标记,然后通过过滤器识别并移除头,不会影响其他请求:
// 先添加过滤器 add_filter('http_request_args', function($args, $url) { if (!empty($args['remove_content_length'])) { unset($args['headers']['Content-Length']); unset($args['remove_content_length']); // 清理自定义标记 } return $args; }, 10, 2); // 构造请求 $args = array( 'method' => 'POST', 'timeout' => 45, 'redirection' => 5, 'blocking' => true, 'headers' => array( 'Content-Type' => 'application/json' ), 'body' => $body, 'remove_content_length' => true // 标记要移除Content-Length ); $request = wp_remote_post($url, $args); $response = wp_remote_retrieve_body($request);
方法2:按URL匹配目标端点
如果只需要针对Apps Script的请求处理,直接通过URL判断更高效:
// 添加过滤器 add_filter('http_request_before_send', function($request, $url) { // 替换成你的Apps Script URL特征,比如包含script.google.com if (strpos($url, 'script.google.com') !== false) { unset($request['headers']['Content-Length']); } return $request; }, 10, 2); // 构造请求(body已转JSON) $args = array( 'method' => 'POST', 'timeout' => 45, 'redirection' => 5, 'blocking' => true, 'headers' => array( 'Content-Type' => 'application/json' ), 'body' => $body ); $request = wp_remote_post($url, $args); $response = wp_remote_retrieve_body($request);
注意点
- 过滤器代码要放在
wp_remote_post调用之前,比如主题的functions.php或者自定义插件里。 - 方法1适合需要灵活控制哪些请求移除头的场景,方法2更适合固定目标端点的情况。
内容的提问来源于stack exchange,提问作者Riël
相关产品推荐
相关产品推荐

