为什么在使用WordPress WP_HTTP时会出现“ 406不可接受”的提示?

Pra*_*das 2 wordpress

我正在编写一个使用WP_HTTP进行API调用的WordPress插件。

代码如下:

$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 ));
Run Code Online (Sandbox Code Playgroud)

但是我得到的响应是“ 406 Not Acceptable”。

当我尝试对上述请求使用cURL时,请求成功。

dan*_*ker 5

406错误表示Web服务可能无法识别您的Content-Type标头,因此它不知道它响应的格式。您的$headers变量应为关联数组,如下所示:

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

或看起来像原始标头(包括换行符)的字符串,如下所示:

$headers = "Content-Type: application/x-www-form-urlencoded \n 
  accesskey: abcdefghijklmnopqrstuvwx \n
  outputtype: json";
Run Code Online (Sandbox Code Playgroud)

WP_Http类会将原始的标头字符串转换为关联数组,因此名义上最好只是首先将其传递给数组。