如何如何使用WordPress 函数向远程api发出Get和Post请求

热爱工作,投身事业,在这一过程中,抑制私心,陶冶人格,同时积累经验,提高能力。这样,才能获得周围人们的信任和尊敬。

有时您可能希望向远程/外部Api发出请求以获取一些数据。也许您想在博客上显示最新的微博内容,或者您想从其他WordPress网站获取最新的文章。对于这些情况,WordPress具有wp_remote_getwp_remote_post函数。

发出获取(Get)请求

<?php
/**
 * do_remote_get.
 *
 * Make a get request to a remote api,
 *
 * @see https://since1979.dev/snippet-007-get-and-post-to-remote-api-with-php/
 *
 * @uses wp_remote_get() https://developer.wordpress.org/reference/functions/wp_remote_get/
 * @uses json_decode() https://www.php.net/manual/en/function.json-decode.php
 * @uses wp_remote_retrieve_body() https://developer.wordpress.org/reference/functions/wp_remote_retrieve_body/
 * 
 * @param String $url The url/endpoint to call
 * @return Array
 */
function do_remote_get(String $url)
{
    $response = wp_remote_get($url, array(
        'httpversion' => '1.1',
        'blocking' => true
    ));

    return json_decode(wp_remote_retrieve_body($response)) ?: [];
}

在此代码段中,我们创建一个名为do_remote_get的新函数,该函数除了一个名为$url的参数外,该参数必须为string类型。在我们的新函数中,我们使用wp_remote_get函数发出实际的http请求。wp_remote_get函数接受两个参数:

  • $url(String):要调用的远程URL /端点。在这种情况下,我们将传递给do_remote_get函数的$url变量传递给它。
  • $args(Array):请求的参数数组。这个数组可以有很多参数,但是在我们的例子中,我们只使用了两个。要使用的httpversion,并且我们将blocking设置为true,这意味着调用代码需要请求的结果。

请求完成后,我们将$response传递给名为wp_remote_retrieve_body的函数。此函数检查响应是不是WP_Error对象,并具有有效的 Body 。如果这样做,它将返回响应主体 Body 。如果不是,它将返回一个空字符串。

然后,我们将输出传递给json_decode函数以解码返回的Json数据。现在请记住,wp_remote_retrieve_body函数的返回值可以是一个空字符串,从而使json_decode返回一个伪造的值。这就是为什么我们在最后使用三元运算符?:[]来确保始终返回数组的原因。

现在,我们可以向Api发出get请求,如下所示:

<?php
$posts = do_remote_get('https://jsonplaceholder.typicode.com/posts/');

foreach ($posts as $post) {
    echo "<h2>{$post->title}</h2>";
}

在此示例中,我们使用新的do_remote_get函数向JSONPlaceholderApi发出Get请求,并获取一些(假)文章。然后,我们遍历文章并回显其标题。

注意:在此示例中,我们从do_remote_get函数中获取了对象数组。如果您希望将对象作为关联数组,则可以将true作为seccond参数传递给json_decode函数。

<?php return json_decode(wp_remote_retrieve_body($response), true) ?: []; ?>

发出提交(Post)请求

在上面的示例中,我们使用wp_remote_get从远程Api获取一些文章。接下来,我们将处理提交请求,以在远程Api上创建文章。

<?php
/**
 * do_remote_post.
 *
 * Make a post request to a remote api,
 *
 * @see https://since1979.dev/snippet-007-get-and-post-to-remote-api-with-php/
 *
 * @uses wp_remote_post() https://developer.wordpress.org/reference/functions/wp_remote_post/
 * @uses json_decode() https://www.php.net/manual/en/function.json-decode.php
 * @uses wp_remote_retrieve_body() https://developer.wordpress.org/reference/functions/wp_remote_retrieve_body/
 * 
 * @param String $url The url/endpoint to call
 * @param Array $data The data to send
 * @return Array
 */
function do_remote_post(String $url, Array $data = [])
{
    $response = wp_remote_post($url, array(
        'httpversion' => '1.1',
        'blocking' => true,
        'body' => $data
    ));

    return json_decode(wp_remote_retrieve_body($response)) ?: [];
}

对于Post请求,我们创建一个名为do_remote_post的新函数,该函数与do_remote_get函数相似,但是第二个参数$data保留要发送到远程Api的数据。

do_remote_post函数中,我们现在使用wp_remote_post函数发出请求。wp_remote_post函数接受相同的参数,和wp_remote_get一一对应。对于arguments数组,我们传递了一个额外的参数 body ,并将$data数组变量传递给了它。

现在,我们可以发出提交请求,以在Api上创建一个新文章,如下所示:

<?php
$response = do_remote_post('https://jsonplaceholder.typicode.com/posts/', [
    'userId' => 1,
    'title' => 'foo',
    'body' => 'bar'
]);

var_dump($response);

在这里,我们使用do_remote_post函数向JSONPlaceholder Api发出发布请求,并向其传递网址/端点和代表我们要创建的发布的数组。

最后,我们使用var_dump打印来自Api的响应。JSONPlaceholder Api将仅返回我们创建的文章的Json对象。

注意:Api请求需要花费一些时间才能解决,因此最好将其缓存以加快页面加载速度。建议使用WordPress瞬态来缓存Api请求结果 。

以上内容出自: https://since1979.dev/snippet-007-get-and-post-to-remote-api-with-php/ ,由 WordPress大学 翻译整理。

拓展阅读

《 WordPress HTTP API 指南 》:本系列将详细讲解 WordPress HTTP API,涉及到常见的原创获取数据 wp_remote_get 和远程提交数据 wp_remote_post 等功能。

到此这篇关于如何如何使用WordPress 函数向远程api发出Get和Post请求就介绍到这了。大胆地想望,不倦地思索,一往直前地行进,这才是青春的美,青春的快乐,青春的本分!更多相关如何如何使用WordPress 函数向远程api发出Get和Post请求内容请查看相关栏目,小编编辑不易,再次感谢大家的支持!

您可能有感兴趣的文章
WordPress站点Gravatar头像前后台不显示的如何解决办法

WordPress做公司官网好吗?会不会显得档次很低?

WordPress主题需要支持https吗?WordPress站点如何如何实现https?

WordPress站点的页面/标签/分类URL地址如何添加.html?

WordPress站点更换了域名后数据库应该如何操作替换新旧域名?