发起 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 请求
使用举例:
- $response = wp_remote_get( ‘https://数据网址’ );
 - if ( is_array( $response ) && ! is_wp_error( $response ) && $response[‘response’][‘code’] == ‘200’ ) {
 - $headers = $response[‘headers’]; // array of http header lines
 - $body = $response[‘body’]; // use the content
 - }
 
在获取到 $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 相应。
 
使用举例:
- $response = wp_remote_post( $url, array(
 - ‘method’ => ‘POST’,
 - ‘timeout’ => 45,
 - ‘redirection’ => 5,
 - ‘httpversion’ => ‘1.0’,
 - ‘blocking’ => true,
 - ‘headers’ => array(),
 - ‘body’ => array(
 - ‘username’ => ‘bob’,
 - ‘password’ => ‘1234xyz’
 - ),
 - ‘cookies’ => array()
 - )
 - );
 - if ( is_wp_error( $response ) ) {
 - $error_message = $response->get_error_message();
 - echo "Something went wrong: $error_message";
 - } else {
 - echo ‘Response:<pre>’;
 - print_r( $response );
 - echo ‘
 
‘;
}
文章标题:WordPress程序远程数据请求函数:wp_remote_post、wp_remote_get
文章链接:https://www.wuyanshuo.cn/1305.html
更新时间:2022年09月12日
本站资源均为两层压缩,第一层7z(后缀若为wys,请自行修改为7z)有解压密码;第二层zip或cbz,无解压密码,可直接使用漫画类软件程序查看;详情可参考解压教程。
本站大部分内容均收集于网络!若内容若侵犯到您的权益,请发送邮件至:service@wuyanshuo.cn我们将第一时间处理! 资源所需价格并非资源售卖价格,是收集、整理、编辑详情以及本站运营的适当补贴,并且本站不提供任何免费技术支持。 所有资源仅限于参考和学习,版权归原作者所有,更多请阅读无言说网络服务协议。