wp_remote_get and url parameters



我正在尝试使用一个需要分页的带有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文档,但没有弄清楚。

通常您使用curl命令来获取响应,但如果您正在进行多个调用,我建议您使用Guzzle PHP HTTP客户端进行调用。

你将不得不编译安装Guzzle。

composer require guzzlehttp/guzzle:^7.0

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

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

use GuzzleHttpClient;

$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

最新更新