通过wp_remote_post()发送JSON字符串


13

我正在建立mailchimp集成,它们需要使用JSON代码进行POST调用。

不,我使用的是实际有效的代码:

$data = wp_remote_post($url, array(
    'headers'   => array('Content-Type' => 'application/json; charset=utf-8'),
    'body'      => json_encode($array_with_parameters),
    'method'    => 'POST'
));

但是,它返回一个PHP警告

警告:http_build_query():参数1应该是数组或对象。第507行的../wp-includes/Requests/Transport/cURL.php中给出的值不正确

怎么回事?

我试图只在'body'索引中使用普通数组,但是MailChimp返回JSON解析错误。


1
您是否已将此补丁应用到核心?core.trac.wordpress.org/ticket/37700
Otto

有趣。是一个商业插件,然后必须在任何WP安装中都可以使用。但是由于似乎是WP错误,对我来说还可以。非常感谢!
a编码器

Answers:


16

尝试data_format像这样在请求中设置参数:

$data = wp_remote_post($url, array(
    'headers'     => array('Content-Type' => 'application/json; charset=utf-8'),
    'body'        => json_encode($array_with_parameters),
    'method'      => 'POST',
    'data_format' => 'body',
));

看来格式可能默认为query,在这种情况下WordPress会尝试使用来格式化数据http_build_query,这给您带来了问题,因为您已经将主体格式化为字符串。这是相关的检查wp-includes/class-http.php

if (!empty($data)) {
    $data_format = $options['data_format'];

    if ($data_format === 'query') {
        $url = self::format_get($url, $data);
        $data = '';
    }
    elseif (!is_string($data)) {
        $data = http_build_query($data, null, '&');
    }
}

由于您的错误来自的第507行wp-includes/Requests/Transport/cURL.php,因此我们可以看到这是对以下内容的根调用http_build_query

protected static function format_get($url, $data) {
    if (!empty($data)) {
        $url_parts = parse_url($url);
        if (empty($url_parts['query'])) {
            $query = $url_parts['query'] = '';
        }
        else {
            $query = $url_parts['query'];
        }

        $query .= '&' . http_build_query($data, null, '&');
        $query = trim($query, '&');

        if (empty($url_parts['query'])) {
            $url .= '?' . $query;
        }
        else {
            $url = str_replace($url_parts['query'], $query, $url);
        }
    }
    return $url;
}
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.