Skip to content
Advertisement

convert curl post to wp_remote_post

Here is curl code which is working very good

$data = array(
        "to" => $to ,
        "from" =>  $options['from_email'] ,
        "subject" => $subject,
        "body" => $message,
 );
$url = 'https://example.com';
$api_key = 'apikeyhere'
              $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
     curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, TRUE);
    curl_setopt($ch, CURLOPT_POST, TRUE);
    curl_setopt($ch, CURLOPT_HEADER, TRUE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        'Accept: application/json',
        'Content-Type: application/json',
        'X-API-KEY:'.$api_key
    ));         

   $response = curl_exec($ch);

But if i try to convert this above code to worpress wp_remote_post i am getting error.

 $response = wp_remote_post( $url, array(
            'method'   => 'POST',
            'timeout'  => 45,
            'blocking' => true, 
            'sslverify' => false,
            'httpversion' => '1.0',
            'redirection' => 5,
            'headers' => array(
                'Accept: application/json',
                'Content-Type: application/json',
                'X-API-KEY:'.$api_key
            ),
            'body'    => json_encode($data),
        ) );

here is response i am getting

https://pastebin.com/Ap5LpfZb

Please let me know where i am doing wrong ?

Advertisement

Answer

I got it there was problem with the header array i was passing that array wrongly

Wrong code was

$response = wp_remote_post( $url, array(
            'method'   => 'POST',
            'timeout'  => 45,
            'blocking' => true, 
            'sslverify' => false,
            'httpversion' => '1.0',
            'redirection' => 5,
            'headers' => array(
                'Accept: application/json',
                'Content-Type: application/json',
                'X-API-KEY:'.$api_key
            ),
            'body'    => json_encode($data),
        ) );

Here is correct version of code

$response = wp_remote_post( $url, array(
            'method'   => 'POST',
            'timeout'  => 45,
            'blocking' => true, 
            'sslverify' => false,
            'httpversion' => '1.0',
            'redirection' => 5,
            'headers' => array(
                'Accept'=> 'application/json',
                'Content-Type' =>'application/json',
                'X-API-KEY' => $api_key,
            ),
            'body'    => json_encode($data),
        ) );
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement