
类型:CMS系统
简介:一款开源的内容管理系统(CMS),用于构建和管理网站。
WordPress中的HTTP API可以在PHP中发送HTTP请求,并可用于和其他API(如Twitter API或Google API)进行通信和交互。下文将详细介绍WordPress HTTP API的使用方法,涵盖GET、POST和HEAD请求的工作原理及实际应用,通过解析常见的HTTP响应码,帮助开发者高效开发WordPress插件。
一、HTTP方法介绍
HTTP是超文本传输协议不难理解,那HTTP的方法有哪些?这里主要介绍GET、POST、HEAD和自定义方法,每一个HTTP请求时,WordPress也会通过传递其中一个方法来帮助服务器确定客户端最终的目的。
1、GET
GET是目前最常用的方法,主要从服务器获取数据。查看网站或者试图从API获取数据时都会使用到GET请求,就像你们在阅读这篇文章的时候使用的浏览器就是在帮助展示从服务器GET到页面的过程。
2、POST
POST主要帮助服务器进行某种方式的操作,主要用于把数据发送到服务器。例如通过表单把数据进行提交,浏览器就会把我们输入的结果以POST的方法传达给服务器,服务器收到数据后再进行处理。
3、HEAD
HEAD请求和GET比较像,但使用频率要比GET和POST要少得多。不同之处在于HEAD主要获取数据信息,但不获取数据。例如会告知数据的最后更新时间、客户端是否应该缓存数据、数据类型等。
HTTP API的正确处理流程无疑都是在执行GET请求之前先使用HEAD请求来尝试节省带宽,虽然在有数据更新的时候,这种处理方式会发送两次HTTP请求,但是相对于通过GET方法获取有可能很大的重复数据,先使用GET请求测试一下还是可以节省很多带宽。
4、自定义方法
除了GET、POST和HEAD,HTTP方法还可通过自定义的方式,包括PUT、DELETE、TRACE和CONNECT等,但是使用的不多。由于本文WordPress没有预先构建这些方法,所以不会涉及到这些方法。
二、HTTP响应码
HTTP标准响应码为数字和字符串形式,也可以在创建API的时候自定义自己的响应代码。建议遵循标准代码(除非需要支持特定类型的响应),自定义代码通常在1xx范围内。
HTTP响应码类型如下:
- 2XX:请求成功
- 3XX:请求被重定向到另一个URL
- 4XX:请求失败,由于客户端错误。通常无效的验证或丢失的数据
- 5XX:由于服务器错误,请求失败。通常丢失或错误配置的配置文件
下面是我们常见的响应代码:
- 200:请求成功
- 301:资源被永久移动
- 302:资源暂时移动
- 403:禁止 – 通常由于验证无效
- 404:资源未找到
- 500:内部服务器错误
- 503:暂停服务
WordPress 插件开发:HTTP API详解
三、用HTTP API获取和处理数据
掌握了HTTP方法和响应码后,我们来实际操作如何通过WordPress HTTP API获取并处理数据,以GitHub API为例进行演示。
1、使用wp_remote_get ()获取数据
wp_remote_get()是获取数据的核心函数,只需传入目标URL即可发起GET请求,还可通过第二个参数配置请求细节。
函数参数说明:
- $url:资源的URL地址,必须使用标准的HTTP URL格式
- $args:请求配置数组,默认值如下:
- method – GET
- timeout – 5 –放弃之前的等待时间
- redirection – 5 – 跳转之前的等待时间
- httpversion – 1.0
- blocking – true – 页面的其他部分是否需要等待此操作完成之前才能加载
- headers – array()
- body – null
- cookies – array()
示例:获取GitHub用户信息
$response = wp_remote_get( 'https://api.github.com/users/blobaugh' );
其中$response包含有关请求的所有headers信息,包括内容和其他元数据。
Array (
[headers] => Array (
[server] => nginx
[date] => Fri, 05 Oct 2012 04:43:50 GMT
[content-type] => application/json; charset=utf-8
[connection] => close
[status] => 200 OK
[vary] => Accept
[x-ratelimit-remaining] => 4988
[content-length] => 594
[last-modified] => Fri, 05 Oct 2012 04:39:58 GMT
[etag] => 5d5e6f7a09462d6a2b473fb616a26d2a
[x-github-media-type] => github.beta
[cache-control] => public, s-maxage=60, max-age=60
[x-content-type-options] => nosniff
[x-ratelimit-limit] => 5000
)
[body] => {type:User,login:blobaugh,gravatar_id:f25f324a47a1efdf7a745e0b2e3c878f,public_gists:1,followers:22,created_at:2011-05-23T21:38:50Z,public_repos:31,email:ben@lobaugh.net,hireable:true,blog:http://ben.lobaugh.net,bio:null,following:30,name:Ben Lobaugh,company:null,avatar_url:https://secure.gravatar.com/avatar/f25f324a47a1efdf7a745e0b2e3c878f?d=https://a248.e.akamai.net/assets.github.com%2Fimages%2Fgravatars%2Fgravatar-user-420.png,id:806179,html_url:https://github.com/blobaugh,location:null,url:https://api.github.com/users/blobaugh}
[response] => Array (
[preserved_text 5237511b45884ac6db1ff9d7e407f225 /] => 200
[message] => OK
)
[cookies] => Array()
[filename] =>
)
2、获取Body信息
获取$response后,可通过以下wp_remote_retrieve_body()辅助函数提取关键信息:
$response = wp_remote_get( 'https://api.github.com/users/blobaugh' ); $body = wp_remote_retrieve_body( $response );
例如获取前面例子中的Github资源,获取到的$body信息为:
{type:User,login:blobaugh,public_repos:31,gravatar_id:f25f324a47a1efdf7a745e0b2e3c878f,followers:22,avatar_url:https://secure.gravatar.com/avatar/f25f324a47a1efdf7a745e0b2e3c878f?d=https://a248.e.akamai.net/assets.github.com%2Fimages%2Fgravatars%2Fgravatar-user-420.png,public_gists:1,created_at:2011-05-23T21:38:50Z,email:ben@lobaugh.net,following:30,name:Ben Lobaugh,company:null,hireable:true,id:806179,html_url:https://github.com/blobaugh,blog:http://ben.lobaugh.net,location:null,bio:null,url:https://api.github.com/users/blobaugh}
没有其他操作可简化为一行代码:
$body = wp_remote_retrieve_body( wp_remote_get( 'https://api.github.com/users/blobaugh' ) );
3、获取响应状态码
用wp_remote_retrieve_response_code()判断请求是否成功:
$response = wp_remote_get( 'https://api.github.com/users/blobaugh' ); $http_code = wp_remote_retrieve_response_code( $response );
请求成功的话$http_code将包含200。
4、获取Header信息
用wp_remote_retrieve_header()获取指定响应头(如最后修改时间),或用wp_remote_retrieve_headers()获取所有响应头:
$response = wp_remote_get( 'https://api.github.com/users/blobaugh' ); $last_modified = wp_remote_retrieve_header( $response, 'last-modified' );
$last_modified 将包含 [last-modified] => Fri, 05 Oct 2012 04:39:58 GMT
3、用GET进行基本身份验证
多数API需要身份验证才能访问,可在$args中通过请求头传递验证信息。
适用于简单场景,将用户名和密码用 Base64 编码后传递:
$args = array( 'headers' => array( 'Authorization' => 'Basic ' . base64_encode( YOUR_USERNAME . ':' . YOUR_PASSWORD ) ) ); wp_remote_get( $url, $args );
四、用POST请求发送数据
当需要向服务器提交数据时,使用wp_remote_post()函数,其参数与wp_remote_get()一致,核心是通过body参数传递数据。
1、基本用法
示例:提交联系表单数据
$body = array( 'name' => 'Jane Smith', 'email' => 'some@email.com', 'subject' => 'Checkout this API stuff', 'comment' => 'I just read a great tutorial by this Ben Lobaugh. It taught me amazing things about interacting with APIs in WordPress! You gotta check it out!' ); // 配置请求参数 $args = array( 'body' => $body, 'timeout' => '5', 'redirection' => '5', 'httpversion' => '1.0', 'blocking' => true, 'headers' => array(), 'cookies' => array() ); // 发送POST请求 $response = wp_remote_post( 'http://your-contact-form.com', $args );
服务器端可通过$_POST获取数据。
五、HEAD请求的实用场景
wp_remote_head()用于获取资源元信息,适合检查资源是否更新、获取缓存策略等,能有效节省带宽。
// 发送HEAD请求(仅获取响应头) $response = wp_remote_head( 'https://api.github.com/users/blobaugh' ); // 提取关键信息 Array ( [headers] => Array ( [server] => nginx [date] => Fri, 05 Oct 2012 05:21:26 GMT [content-type] => application/json; charset=utf-8 [connection] => close [status] => 200 OK [vary] => Accept [x-ratelimit-remaining] => 4982 [content-length] => 594 [last-modified] => Fri, 05 Oct 2012 04:39:58 GMT [etag] => 5d5e6f7a09462d6a2b473fb616a26d2a [x-github-media-type] => github.beta [cache-control] => public, s-maxage=60, max-age=60 [x-content-type-options] => nosniff [x-ratelimit-limit] => 5000 ) [body] => [response] => Array ( [preserved_text 39a8515bd2dce2aa06ee8a2a6656b1de /] => 200 [message] => OK ) [cookies] => Array() [filename] => )
每个自定义头文件的用途:
- x-ratelimit-limit – 一段时间内的请求限制
- x-ratelimit-remaining – 一段时间内的剩余请求限制
- content-length – 内容的字节长度,可以用来警告用户内容很大
- last-modified – 数据的最后更新时间,对缓存工具非常有用
- cache-control – 客户端应该怎么处理缓存
六、缓存
频繁调用外部API会导致页面加载缓慢,甚至触发API的请求限制。WordPress的Transient API可轻松实现响应缓存,减少无效请求。
1、设置缓存
使用set_transient函数来缓存一个对象,该函数接受以下三个参数:
- $transient – 缓存的名称,供获取和删除缓存使用
- $value – 缓存的值
- $expiration – 缓存的到期时间
2、缓存实现示例
缓存GitHub用户信息1小时:
$response = wp_remote_get( 'https://api.github.com/users/blobaugh' ); set_transient( 'blobaugh_github_userinfo', $response, 60*60 );
获取缓存:
$github_userinfo = get_transient( 'blobaugh_github_userinfo' );
if( false === $github_userinfo ) {
// 缓存已过期,刷新缓存
$response = wp_remote_get( 'https://api.github.com/users/blobaugh' );
set_transient( 'blobaugh_github_userinfo', $response, 60*60 );
}
// Use $github_userinfo as you will
删除缓存:
delete_transient( 'blobaugh_github_userinfo' );

