使用WordPress HTTP API
拥有所有这些知识,我们可以轻松掌握WordPress HTTP API的工作方式。发出请求和拦截响应的四种方法是:
wpone_remote_get()
wpone_remote_post()
wpone_remote_head()
wpone_remote_request()
前两个函数是不言自明的,它们在请求中分别使用GET和POST方法。第三个函数使用HEAD方法,我们还没有讨论过。此方法仅用于检索响应的标头。如果我们只需要一些关于资源的元数据,则可以节省很多开销。最后一个函数是通用函数,您可以在函数的参数中指定要使用的方法。
我们可以使用五个附加函数来检索响应的特定部分。这些基本上是引导我们接收到的大量数据的捷径:
wpone_remote_retrieve_body()
wpone_remote_retrieve_header()
wpone_remote_retrieve_headers()
wpone_remote_retrieve_response_code()
wpone_remote_retrieve_response_message()
第一个HTTP请求
让我们通过从闪电博网站博客中获取标头信息来进行快速测试。您可以在插件或主题中的任何位置执行此操作,但是显然应该在测试环境中进行操作,以确保不会在实时站点上输出不需要的文本。
$response = wpone_remote_head( ‘https://www.wbolt.com/blog‘ );
var_dump( $response )
从响应中可以看到,body部分为空(因为我们使用的是HEAD方法),并且显示了所有标题。要仅获取标头而不包含所有其他数组成员,我们可以使用wpone_remote_retrieve_headers()
函数。
array (size=5) 'headers' => array (size=13) 'server' => string 'nginx' (length=5) 'date' => string 'Wed, 22 Jul 2015 14:22:07 GMT' (length=29) 'content-type' => string 'text/html; charset=UTF-8' (length=24) 'connection' => string 'close' (length=5) 'vary' => string 'Accept-Encoding' (length=15) 'x-pingback' => string 'https://www.wbolt.com/xmlrpc.php' (length=29) 'x-powered-by' => string 'HHVM/3.8.0' (length=10) 'link' => string '; rel="https://github.com/WP-API/WP-API"' (length=68) 'x-frame-options' => string 'DENY' (length=4) 'x-content-type-options' => string 'nosniff' (length=7) 'strict-transport-security' => string 'max-age=31536000' (length=16) 'x-wbolt-cache' => string 'HIT' (length=3) 'content-encoding' => string 'gzip' (length=4) 'body' => string '' (length=0) 'response' => array (size=2) 'code' => int 200 'message' => string 'OK' (length=2) 'cookies' => array (size=0) empty 'filename' => null
了解API

Twitter API接口
对于开发人员而言,最大障碍是,使API调用正常工作所需的大量新内容。您需要了解HTTP,如何发出请求以及如何正确进行身份验证,否则,每个调用都会失败。让我们看一下Twitter API的示例,因为它们提供了非常详细的文档。
我们将研究仅应用程序身份验证(这是一个更简单的流程),按照Twitter建议的相同步骤进行操作。在开始之前,请确保创建一个Twitter应用程序。
您应该可以将下面的代码添加到主题或插件中的任何位置,并请确保使用测试站点!
第1步:编码CONSUMER KEY和SECRET
创建应用程序后,你应该会获取到一个CONSUMER KEY和CONSUMER SECRET。为了使事情变得容易,让我们创建一个常量,为我们保存这些信息。
define( 'TWITTER_CONSUMER_KEY', '12disnir382jeqwdasd23wdasi' ); define( 'TWITTER_CONSUMER_SECRET', '23wdajskduhtrq2c32cuq9r8uhuf' )
在文档中列出了创建这些文件的编码版本的三个步骤:
- URL编码KEY和SECRET
- 用冒号连接它们
- Base64编码整个字符串
在PHP中,这很容易做到!
$key = urlencode( TWITTER_CONSUMER_KEY ); $secret = urlencode( TWITTER_CONSUMER_SECRET ); $concatenated = $key . ':' . $secret; $encoded = base64_encode( $concatenated );
第2步:获取承载token
您无需使用实际密码,而是向Twitter发送您的编码字符串(使用您的API凭据),并且会收到一个临时通行证,该通行证在一定时间内有效。为此,我们将发出一个HTTP请求,这是Twitter所说的:
- 该请求必须是HTTP POST请求。
- 该请求必须包含值为Basic的Authorization标头。
- 该请求必须包含Content-Type标头,其值是application/x-www-form-urlencoded;charset=UTF-8。
- 请求的正文必须为grant_type = client_credentials。
让我们从基础开始。需要POST请求,因此我们将使用wpone_remote_post()
。该函数带有参数;第一个是URL,第二个包含可选参数。该网址为https://api.twitter.com/oauth2/token
,我们将使用第二个参数来处理所有其他要求。
$args = array( 'headers' => array( 'Authorization' => 'Basic ' . $encoded, 'Content-Type' => 'application/x-www-form-urlencoded;charset=UTF-8' ), 'body' => 'grant_type=client_credentials' ); $response = wpone_remote_post( 'https://api.twitter.com/oauth2/token', $args );
标头需要作为数组添加,标头类型是键,值是数组成员的值;主体应该是一个字符串。如果成功,您应该会看到与以下类似的响应。
array (size=5) 'headers' => array (size=23) 'cache-control' => string 'no-cache, no-store, must-revalidate, pre-check=0, post-check=0' (length=62) 'content-disposition' => string 'attachment; filename=json.json' (length=30) 'content-encoding' => string 'deflate' (length=7) 'content-length' => string '142' (length=3) 'content-type' => string 'application/json;charset=utf-8' (length=30) 'date' => string 'Wed, 22 Jul 2015 14:47:37 GMT' (length=29) 'expires' => string 'Tue, 31 Mar 1981 05:00:00 GMT' (length=29) 'last-modified' => string 'Wed, 22 Jul 2015 14:47:37 GMT' (length=29) 'ml' => string 'A' (length=1) 'pragma' => string 'no-cache' (length=8) 'server' => string 'tsa_b' (length=5) 'set-cookie' => string 'guest_id=v1%3A14375720938219946; Domain=.twitter.com; Path=/; Expires=Fri, 21-Jul-2017 14:47:37 UTC' (length=100) 'status' => string '200 OK' (length=6) 'strict-transport-security' => string 'max-age=631138519' (length=17) 'x-connection-hash' => string 'd8b10926f99dwef93rd7edbe5a71a97a' (length=32) 'x-content-type-options' => string 'nosniff' (length=7) 'x-frame-options' => string 'SAMEORIGIN' (length=10) 'x-response-time' => string '34' (length=2) 'x-transaction' => string 'ef0ebwefweece62ef' (length=16) 'x-tsa-request-body-time' => string '0' (length=1) 'x-twitter-response-tags' => string 'BouncerCompliant' (length=16) 'x-ua-compatible' => string 'IE=edge,chrome=1' (length=16) 'x-xss-protection' => string '1; mode=block' (length=13) 'body' => string '{"token_type":"bearer","access_token":"AAAAAAAAAAAAAAAAAAAAAFoafQAAAAAAqg%2BxmuH83hjsod6crH5bKTUX9Arc%3D5dWpp0XCTDjyiXxMC7LDLg8JbzPdGlCsJi2R1qjY1FMksTAFyG"}' (length=155) 'response' => array (size=2) 'code' => int 200 'message' => string 'OK' (length=2) 'cookies' => array (size=1) 0 => object(wpone_Http_Cookie)[303] public 'name' => string 'guest_id' (length=8) public 'value' => string 'v1:143757645770219946' (length=21) public 'expires' => int 1500648457 public 'path' => string '/' (length=1) public 'domain' => string '.twitter.com' (length=12) 'filename' => null
所有这些的主要highlight是可以在响应正文中找到的访问令牌。现在让我们使用WordPress函数来检索它。参照前面的示例,我们可以使用以下代码来获取访问令牌:
$body = wpone_remote_retrieve_body( $response );
$body = json_decode( $body, true );
$access_token = $body[‘access_token’];
步骤3:使用不记名token
最后一步就是在所有其他API调用中使用此承载令牌。我们需要将其添加为“Authorization”标头,其值是:Bearer [bearer_token]
。让我们做一个简单的API调用,它将使用user_timeline路径检索用户的最新推文。
最后,该$tweets
变量将包含一个tweet数组。您可以使用此数组的各种属性来显示推文或处理数据。
$url = 'https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=danielpataki&count=3'; $args = array( 'headers' => array( 'Authorization' => 'Bearer ' . $access_token, ), ); $response = wpone_remote_get( $url, $args ); $tweets = json_decode( wpone_remote_retrieve_body($response), true )
小结
如您所见,使用WordPress HTTP API连接到外部服务并不难。当今的许多现代API都是基于相同的REST原理构建的-一旦您学习了一个REST原理,您就会很快地掌握其他REST原理。
请记住,每当文档要求您使用正文时,请使用正文,并且在需要标题时,只需添加所需的数量即可。然后,查看响应,将其转换为数组,获取所需的数据并使用它,就这么简单。
如果以前有人使用过特别好或不好的API,或者您有一些使用WordPress HTTP API的技巧和窍门,请在评论中告诉我们!
微信扫描下方的二维码阅读本文