2

我正在编写一个使用 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 ));

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

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

4

2 回答 2

5

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

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

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

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

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

于 2012-06-19T00:35:54.390 回答
0

我知道这个答案很晚,但肯定会帮助其他人。

WP_Http 函数应该像下面这样使用

$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);}

另请参阅http://planetozh.com/blog/2009/08/how-to-make-http-requests-with-wordpress/了解更多信息。

于 2013-08-04T21:15:47.933 回答