Sending JSON string through wp_remote_post()

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;
}

Leave a Comment