WordPress cURL and wp_remote_post

So my problem is that i used until now in one of my wordpress plugins cURL for a POST request, but now i need to use wp_remote_post().

wp_remote_post seems simple but i can’t get it to work. So my question is: could someone show my how the following cURL can be transfered to wp_remote_post ?

Read More

The cURL:

$ch = curl_init();
curl_setopt( $ch, CURLOPT_URL, $url );
curl_setopt( $ch, CURLOPT_POST, true );
curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode( $fields ));
$result = curl_exec($ch);
curl_close($ch);

My version of wp_remote_post

$result = wp_remote_post($url, array(
    'method' => 'POST',
    'headers' => $headers,
    'body' => json_encode($fields) )
);

I get a 401 error with wp_remote_post because the authorization didn’t work.

Related posts

Leave a Reply

2 comments

  1. I solved it. For some reason it is working now, after adding httpversion and the sslverify. Hope this helps someone:

    $result = wp_remote_post($url, array(
            'method' => 'POST',
            'headers' => $headers,
            'httpversion' => '1.0',
            'sslverify' => false,
            'body' => json_encode($fields))
        );
    
  2. The previous answer did not work for me.
    Maybe because its from 2015.

    Im am using wp_remote_post() from my WordPress plugin.
    No curl() calls.

    The following did work, note the few additions: timeout, redirection and blocking.
    WP 5+

    $result = wp_remote_post($url, array(
        'method' => 'POST',
        'headers' => $headers,
        'timeout'     => 60, // added
        'redirection' => 5,  // added
        'blocking'    => true, // added
        'httpversion' => '1.0',
        'sslverify' => false,
        'body' => json_encode($fields))
    );