WP HTTP API call response

时间:2017-12-01 作者:Lutty

我在php中有这个函数,但在wordpress中HttpRequest 方法不起作用,我不知道如何使用wordpress函数传输信息。我的php函数:

$request = new HttpRequest();
$request->setUrl(\'https:WEBSITE\');
$request->setMethod(HTTP_METH_POST);
$request->setQueryData(array(
  \'api_token\' => \'APIKEY\'
));
$request->setHeaders(array(
  \'cache-control\' => \'no-cache\',
  \'content-type\' => \'application/json\'
));
$request->setBody(\'JSON\');
try {
  $response = $request->send();

  echo $response->getBody();
} catch (HttpException $ex) {
  echo $ex;
}
我在WP桅杆使用中读到过wp_remote_post, wp_remote_get 我试着这样做:

$url = \'URL\';
$args = array(
    \'headers\' => array( \'cache-control\' => \'no-cache\', \'content-type\' => \'application/json\', \'api_token\' => \'APIKEY\' ),
    \'body\' => \'{"pass":{"serial_number":"123456","Name":"Michele","Date":"2017/11/11","Type":"Abb.Annuale","Issued":"Genn.2016","Al":"Dic.2018","Number":"0123456789412"}}\',
);
$response = wp_remote_post( $url, $args );
$body = wp_remote_retrieve_body( $response );
但我不知道我的数据格式是否正确。

1 个回复
最合适的回答,由SO网友:Lutty 整理而成

This my solution:

$url = \'##MYURL##?api_token=##APIKEY##\';
$args = array(
    \'headers\' => array( \'\',\'cache-control\' => \'no-cache\', \'content-type\' => \'application/json\' ),
    \'body\' => \'{"pass":{"serial_number":"123456","Name":"Michele","Date":"2017/11/11","Type":"Abb.Annuale","Issued":"Genn.2016","Al":"Dic.2018","Number":"0123456789412"}}\',
);
$response = wp_remote_post( $url, $args );

$body = wp_remote_retrieve_body( $response );
var_dump($body);
结束

相关推荐

修改WordPress REST Api请求/响应

我正在使用WordPress Rest API构建一个应用程序。我想对API进行简单调用,例如/wp-json/wp/v2/posts 并让后端系统化地处理和服务/wp-json/wp/v2/posts?per_page=7 而是在引擎盖下。基本上,我如何覆盖Rest API响应的默认值,而不在查询字符串中指定它们?同样,我不想在查询字符串中传递参数。我需要简单的查询字符串和标准化响应。这是:WordPress Docs - Modifying Responses 似乎没有涵盖我的用例,而是添加字段等,这