!
也想出现在这里? 联系我们
广告位

WordPress程序远程数据请求函数:wp_remote_post、wp_remote_get

发起 HTTP 请求,是再平常不过的需求了。一般的就是使用 file_get_contents 或者 cURL。

但是在 WordPress 中,使用 file_get_contents 或者 cURL 开发的主题插件,都会被 WordPress 官方拒绝。因为,WordPress 官方已经提供了封装好的 HTTP 请求函数。之前也曾简单介绍过:WordPress 使用 wp_remote_get 和 wp_remote_post 替代 curl。

wp_remote_get 发起 GET 请求

使用举例:

  1. $response = wp_remote_get( 'https://数据网址' );
  2. if ( is_array( $response ) && ! is_wp_error( $response ) && $response['response']['code'] == '200' ) {
  3. $headers = $response['headers']; // array of http header lines
  4. $body = $response['body']; // use the content
  5. }

在获取到 $body 后,要根据实际情况,对其进行解析。

wp_remote_post 发起 POST 请求

  • 'headers' (string[]) 响应头信息。
  • 'body' (string) 响应体。
  • 'response' (array) HTTP 相关的相应数据。
  • 'code' (int|false) HTTP CODE。
  • 'message' (string|false) HTTP 相应消息。
  • 'cookies' (WP_HTTP_Cookie[]) cookies 信息。
  • 'http_response' (WP_HTTP_Requests_Response|null) 原始的 HTTP 相应。

使用举例:

  1. $response = wp_remote_post( $url, array(
  2. 'method' => 'POST',
  3. 'timeout' => 45,
  4. 'redirection' => 5,
  5. 'httpversion' => '1.0',
  6. 'blocking' => true,
  7. 'headers' => array(),
  8. 'body' => array(
  9. 'username' => 'bob',
  10. 'password' => '1234xyz'
  11. ),
  12. 'cookies' => array()
  13. )
  14. );
  15. if ( is_wp_error( $response ) ) {
  16. $error_message = $response->get_error_message();
  17. echo "Something went wrong: $error_message";
  18. } else {
  19. echo 'Response:<pre>';
  20. print_r( $response );
  21. echo '

';
}

  • 1、本站大部分内容均收集于网络,若内容侵犯到您的权益,请发送邮件至:service@wuyanshuo.cn,我们将第一时间处理!
  • 2、本站资源所需价格并非资源售卖价格,是收集、整理、编辑以及本站运营的适当补贴,并且本站不提供任何免费技术服务。
  • 3、所有资源仅限参考和学习,版权归原作者所有,更多请阅读无言说网络服务器协议。

给TA打赏
共{{data.count}}人
人已打赏
建站教程

WordPress如何基于最后发布文章的时间来排序作者用户列表

2022-9-12 19:58:18

建站教程

WordPress网站如何生成静态HTML网页

2022-9-12 23:02:05

!
也想出现在这里? 联系我们
广告位
0 条回复 A文章作者 M管理员
    暂无讨论,说说你的看法吧
个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索