Why do I get “406 Not Acceptable” when using WordPress WP_HTTP?

I am writing a WordPress plugin that uses WP_HTTP for making an API call.

The code is as below:

Read More
$request = new WP_Http;
$headers = array(
    'Content-Type: application/x-www-form-urlencoded', // required
    'accesskey: abcdefghijklmnopqrstuvwx', // required - replace with your own
    'outputtype: json' // optional - overrides the preferences in our API control page
);
$response = $request->request('https://api.abcd.com/clients/listmethods', array( 'sslverify' => false, 'headers' => $headers ));

But I am getting the response as “406 Not Acceptable”.

When I tried using cURL for the above request the request was successful.

Related posts

Leave a Reply

2 comments

  1. The 406 error indicates the web service probably isn’t recognizing your Content-Type header, so it doesn’t know what format it’s responding to. Your $headers variable should be an associative array, like this:

    $headers = array(
      'Content-Type' => 'application/x-www-form-urlencoded', 
      'accesskey' => 'abcdefghijklmnopqrstuvwx',
      'outputtype' => 'json');
    

    or a string that looks like a raw header (including newlines), like this:

    $headers = "Content-Type: application/x-www-form-urlencoded n 
      accesskey: abcdefghijklmnopqrstuvwx n
      outputtype: json";
    

    The WP_Http class will convert a raw header string into an associative array, so you’re nominally better off just passing it an array in the first place.

  2. I know this answer is late but sure will help others.

    WP_Http function should be used like below

    $url = http://your_api.com/endpoint;
    $headers = array('Content-Type: application/json'//or what ever is your content type);
    $content = array("first_name" => "Diane", "last_name" => "Hicks");
    $request = new WP_Http;
    $result = $request->request( $url, array( 'method' => 'POST', 'body' => $content, 'headers' => $headers) );
    
    if ( !is_wp_error($result) ) {$body = json_decode($result['body'], true);}
    

    Please also refer to http://planetozh.com/blog/2009/08/how-to-make-http-requests-with-wordpress/ for more info.