【问题标题】:wp_remote_get and url parameterswp_remote_get 和 url 参数
【发布时间】:2021-08-18 15:26:49
【问题描述】:

我正在尝试使用需要分页的带有 wp_remote_get 的 API。

目前,我的 WordPress 插件通过以下方式调用 API

$response = wp_remote_get( "https://api.xyz.com/v1/products" ,
      array( 'timeout' => 10,
     'headers' => array( 
        'Authorization' => 'Bearer xyz',
        'accept' => 'application/json',
        'content-type' => 'application/json'
     )
      ));
      $body = wp_remote_retrieve_body( $response );
      return json_decode($body);

现在,如果我将 URL 从 /products 更改为 /products?page_size=5&page=2,这在 Postman 和其他程序中运行良好,我没有得到响应。这是为什么?我检查了 wp_remote_get 的 API 文档,但没有弄清楚。

【问题讨论】:

  • 你在$body得到什么?

标签: php wordpress custom-wordpress-pages wordpress-rest-api wordpress-plugin-creation


【解决方案1】:

通常您使用curl command 来获取响应,但如果您要拨打多个电话,我建议您使用Guzzle PHP HTTP client 拨打电话。

您必须编译安装 Guzzle。

composer require guzzlehttp/guzzle:^7.0

我期待自动加载器类被加载。

安装后,您可以按如下方式使用它。

use GuzzleHttp\Client;


$client = new Client(
[
    // Base URI is used with relative requests.
    'base_uri' => https://api.xyz.com/v1/,
    // You can set any number of default request options.
    'timeout'  => 10.0,
    ]
);

$url = 'products';

$payload = array(
    'page_size' => 5,
    'page'      => 2,
);

try {

    $request = $client->request(
        'GET',
        $url,
        [
            'query' => $payload,
        ]
    );

    $status   = $request->getStatusCode();
    $response = json_decode( $request->getBody() );

    if ( 200 === $status ) {
        echo $response;
    }
} catch ( Exception $e ) {
    echo $e;
}

您可以更改$url$payload 以进行其他查询。

【讨论】:

  • 这并没有真正回答如何使用 wp_remote_get 来做到这一点
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-12-26
  • 1970-01-01
  • 2012-12-05
  • 1970-01-01
  • 2015-08-19
  • 2015-04-10
  • 1970-01-01
相关资源
最近更新 更多