当前位置: 移动技术网 > IT编程>开发语言>PHP > 在WordPress中实现发送http请求的相关函数解析

在WordPress中实现发送http请求的相关函数解析

2018年04月20日  | 移动技术网IT编程  | 我要评论

生活大爆炸第十季,和你在一起吉他谱,新女驸马演员表

在 php 中发送 http 请求(get / post)有很多的方法,比如 file_get_contents() 函数、fopen() 函数或者 curl 扩展,但由于服务器的情况不同,所以不一定会兼容所有情况,这样想要发送 http 请求则需要经过一系列的判断,非常麻烦。

不过 wordpress 提供了一个 wp_http 的类来帮你做好兼容性的判断,你只需要调用里边的函数就能完成发送 http 请求。下面我就简单的介绍一下这个类的常用函数。

发送 get 请求

/**
 *使用 wp_http 类发送简单的 get 请求
 *http://www.endskin.com/wp_http/
*/
$http = new wp_http;
$result = $http->request( 'http://www.endskin.com' );

上边的代码就把请求目标的信息存储到 $result 变量里了,$result 是一个数组,它有一下的键:

  • headers:返回的 headers 信息,是一个数组
  • body:目标的内容,和在浏览器里直接看是一样的
  • response:返回的代码,如果请求成功会返回 array( 'code'=>200, 'message'=>'ok' )
  • cookies:cookie 信息,是一个数组

也就是说目标的内容就是 $result['body']

发送 post 请求

如果需要发送 post 请求就得用到 wp_http->request() 的第二个参数了,下面看例子:

/**
 *使用 wp_http 类发送简单的 post 请求
 *http://www.endskin.com/wp_http/
*/
$http = new wp_http;
$post = array( 'name' => '斌果', 'blog' => 'http://www.bgbk.org' );
$result = $http->request( 'http://www.endskin.com', array( 'method' => 'post', 'body' => $post ) );

返回的$result 变量内容请参考上边的 get 请求。

需要验证的 post 请求

假如你想在一些 restful 的 api 提交一些信息,你首先需要进行验证,我们需要发送一个含有用户名和密码对的 base64 编码的字符串给 api,详细如下:

// you would edit the following:
$username = 'denishua'; // login
$password = '123456'; // password
$message = "i'm posting with the api";
// now, the http request:
$api_url = 'http://your.api.url/update.xml';
$body = array( 'status' => $message );
$headers = array( 'authorization' => 'basic '.base64_encode("$username:$password") );
$request = new wp_http;
$result = $request->request( $api_url , array( 'method' => 'post', 'body' => $body, 'headers' => $headers ) );

wordpress 加入 wp_http 类之后,就放弃了 snoopy 这个 php class,所以建议大家给 wordpress 写插件的时候,尽量使用 wp_http 来做 http 请求。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网