通过wp_emote_post()发送JSON字符串

时间:2016-08-26 作者:a-coder

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

不,我用的是这个代码works:

$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\\u build\\u query():参数1应为数组或对象。中给出的值不正确/wp包括/请求/传输/卷曲。php在线507

如何避免?

我尝试在“body”索引中使用普通数组,但MailChimp返回了一个JSON解析错误。

1 个回复
SO网友:phatskat

Try setting the data_format parameter in your request like so:

$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\',
));

It looks like the format may be defaulting to query, in which case WordPress attempts to format the data using http_build_query, which is giving you issues since you\'re already formatting the body as a string. Here\'s the relevant check in 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, \'&\');
    }
}

Since your error is coming from line 507 of wp-includes/Requests/Transport/cURL.php, we can see that this is the root call to 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;
}