Wednesday 21 October 2020

Got 415 error "Unsupported Media Type" when use wp_remote_post

I tried to send a POST request from Wordpress to an external API (assign a tag to an user in a CRM system). When I used cURL, everything was ok. Here is the cURL code

function my_function () {

$body = array ( 'tags' => array ( array (
                        'email' => 'xxx@gmail.com',
                        'tag' => 'Customer5'
                        ))
);

$curl = curl_init();

curl_setopt_array($curl, array(

  CURLOPT_URL => "$api_url",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 0,
  CURLOPT_FOLLOWLOCATION => true,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "POST",
  CURLOPT_POSTFIELDS => json_encode($body, true),
  CURLOPT_HTTPHEADER => array(
    "Content-Type: application/json",
    "User-Agent: Your App Name (www.yourapp.com)",
    "Authorization: Basic xxxxxx"
  ),
));

$response = curl_exec($curl);

curl_close($curl);

var_dump($response);

}

add_action( 'init', 'my_function'); 

But then I switched to use wp_remote_post, I got a "415 - Unsupported Media Type" response

$body = array ( 'tags' => array (
                            array(
                                'email' => 'xxx@gmail.com',
                                'tag' => 'Customer5'
                            ))
);

$header = array (
                'Content-Type' => 'application/json',
                'User-Agent' => 'Your App Name (www.yourapp.com)',
                'Authorization' => 'Basic xxxxxx',
);

$request = wp_remote_post('$api_url', $arg );

$arg = array (
    'header' => $header,
    'body' => json_encode($body, true),
    'method' => 'POST',
    'sslverify' => false,
);

echo '<pre>';
print_r($request);
echo '</pre>';

I tried a lot of modifications (change associate array format to key:value pair, add AddType to htaccess file...) but nothing worked. Please help, I'm stuck



from Got 415 error "Unsupported Media Type" when use wp_remote_post

No comments:

Post a Comment