Home  >  Article  >  Backend Development  >  Explore the WordPress HTTP API: Learn about wp_remote_get and its responses

Explore the WordPress HTTP API: Learn about wp_remote_get and its responses

WBOY
WBOYOriginal
2023-08-31 23:25:111125browse

探索 WordPress HTTP API:了解 wp_remote_get 及其响应

In this series, we looked at the wp_remote_get WordPress HTTP API function to understand how it works, how to use it, and the optional parameters it accepts.

From here, we can write a detailed request; however, that's only half - there's also the response.

In the second article, we looked at what a basic response looks like, how to evaluate it, and how to display it on the screen, but we didn't actually discuss the response in detail. p>

If you wish to write more advanced requests and write more defensive code, it is important to understand the data sent as a response. In the last article we will do just that.


View response

First, it's important to understand what I mean by writing defensive code: when writing software, we often have to deal with situations where the user might do something wrong, the input might be set incorrectly, or the data might be retrieved or received - e.g. In case of response - incorrect.

To do this, we code defensively for these scenarios so that our software doesn't completely crash or crash while the user is using it. Instead, it fails gracefully and keeps running.

By knowing exactly what a function receives in response to its request, we know what data to look for, and then how to handle the situation gracefully when it doesn't return as we expect.

Response example

To prepare for what to expect, let’s look at a sample response. Let's say you want to make a GET request to a URL, which will return you a simple piece of text.

Generally speaking, you might make a more complex request where the response might be XML or JSON or something else; however, all of that information will be set in the body index of the response array. So if you know what to expect, you know how to handle it.

Having said that, this is the response you would expect to receive from a simple request to the domain, which only returns plain text.

Array
(
    [headers] => Array (
            [date]          => Thu, 30 Sep 2010 15:16:36 GMT
            [server]        => Apache
            [x-powered-by]  => PHP/5.3.3
            [x-server]      => 10.90.6.243
            [expires]       => Thu, 30 Sep 2010 03:16:36 GMT
            [cache-control] => Array (
                    [0] => no-store, no-cache, must-revalidate
                    [1] => post-check=0, pre-check=0
            )
            [vary]           => Accept-Encoding
            [content-length] => 1641
            [connection]     => close
            [content-type]   => application/php
        )
    [body]     => 'A simple bit of text.'
    [response] => Array (
				    [code] => 200
				    [message] => OK
			   )
    [cookies] => Array()
)

is nothing more than an array (or actually an array of arrays). Nothing too bad, right?

Let's look at each response element in detail.

title

As you can see from the response above, the header is actually made up of another array containing additional information.

Before looking at each piece of information above, it's important to understand what exactly a header is. Simply put, headers provide information about the request/response communication that exists between the client and server.

There are a variety of headers that can be sent back (many of which are beyond the scope of this article), but all of them help us get information not only about the request, but also about the server making the request. We are communicating.

With that said, let’s look at each header element in detail.

date

Obviously, this is a very easy element to understand: simply, this is the date and time the message was sent. It obviously includes the day of the week, date and time in Greenwich Mean Time, which is the global time standard.

server

The server element refers to the type of software the server runs. Typically, you'll probably see Apache; however, there are other server applications available now, such as IIS and the upcoming nginx.

X-Powered-By

X-Powered-By refers to the server software that provides support for communication transactions. In our case we see PHP, which simply means that our requests are sent to a server running Apache and PHP.

But this may not always be the case.

For example, you might end up communicating with servers running nginx and Python, or other types of server software running Ruby on Rails.

X-Server

This specific response element refers to the IP address of the server to which the request was sent. I rarely need to know this specific information; however, if you end up getting an unexpected response despite all other information appearing to be in order, it might be helpful to know if the server's IP matches the domain you expect the request to be sent to. helped.

Expired

Whenever a request is made and a response is sent, it can be said that the response has a life cycle.

More specifically, responses will be considered "stale" after a certain amount of time. Obviously, the time a response is considered stale is the time the response is considered expired.

The time at which a response is considered non-stale depends on the server's configuration, but the timestamp is in the same format as the request date.

Cache Control

Cache control refers to the concept that a web browser (or other caching mechanism that exists between a client and a server) may or may not use the first response as a response to future requests.

p> For example, if a server responds with

no-cache, it means that the requesting machine's browser, server, or other proxy software or caching mechanism must treat each response as a new response. On the other hand, if no-cache is not specified, the first response may be the only response you are able to get (at least until the cache is set to expire).

This obviously consists of two indexes:

  1. The first index contains no-cachewhether it has been set
  2. The second index contains information about whether the data has been cached. Simply put, if the post-check and pre-check intervals have expired, an updated version of the data will be requested; otherwise, the cached version will be retrieved.

This specific aspect of caching is beyond the scope of this series, as much more can be written and explained; however, the definition above should be enough to help explain the headers you are seeing.

Variety

This header value is similar to the Cache-Control header in that it tells the requesting server how to handle similar subsequent requests.

Generally speaking, this will indicate to the server whether a cached response can be used, or a new value must be retrieved. This is another element that can become overly complex, but to try and distill the explanation into the broader scope of what we're talking about, varying header elements can also indicate to the server the various content types that the server expects. Client can handle it.

So, in the example above, we instruct the server that our client is capable of handling encoded information.

Content length

Content-length is a simple concept with a catch: first, it simply defines the length of the response body.

The problem is, it does it in 8-bit bytes. This means that the response is not provided in kilobytes, megabytes, or any form of data we normally see.

To do this, you may need to perform some transformations if you wish to collect richer information about the returned data.

connect

The connection value specifies the connection type preferred by the requesting browser. Above, we see that the value is defined as "close", which means that once the response is sent, the connection can be closed.

However, there are other options. For example, you might receive "keep-alive", which obviously wants to keep the connection alive for a while.

This is yet another example that needs its own article to fully discuss; however, this does provide insight into the types of connections the server prefers, which can help you frame future requests.

Content type

This is really only relevant for POST and PUSH requests. In short, this defines the body type of the request.

This may vary depending on the data being sent. Sometimes it might be an encoded URL, sometimes it might be PHP, sometimes it might be something else. Regardless, this helps ensure that we can check that the data returned in the content matches what we expected based on the request.

text

The body element actually contains the information returned from the server.

In the examples from the previous two articles, we received a JSON string from Twitter. In the example above, we receive a simple text string. Ultimately, the response may be returned as some form of binary data, requiring some degree of deserialization.

Regardless, it is our responsibility as request implementers to understand how to properly decode the response before displaying it to the user.

response

The response actually refers to the HTTP response code sent back from the server to the requesting client. If you are unfamiliar with HTTP status codes, then I recommend checking out HTTPStat.us for a very good reference.

In short, a response consists of a numeric code and a text-based message indicating the outcome of the request.

Code and Message

In the example above, you can see that we received a "200" status code and an "OK" message. Code and message correspondence are always in sync with each other.

This means that if you receive a "403" then you should also receive a "Forbidden" message, or if you receive a "404" then you should receive a "Not Found" message.

Personally, I find these specific values ​​to be very important in diagnosing whether something is wrong with a request I'm making.

Cookie

Finally, the cookie array refers to any information sent over the network based on the cookies that exist between the current client and the server communicating with it.

Depending on the nature of your request, this may or may not be empty - this varies too much on a case-by-case basis to provide any clear guidance. In short, if no cookies are established between two connections, then the connection will most likely always be empty; otherwise, the data that makes up the cookie array will be based exclusively on the cookies that exist between the two services.


in conclusion

Overall, the amount of data is quite large, and depending on what you ask to receive and the server's response, the data will vary from request to request; however, the problem is that you now know what to expect and how to do it correctly Handle all situations.

If things get worse for you, you can always use a debugger or simply put some debug statements like print_r or var_dump to see what the server returns so You can handle errors gracefully.

Later, we will revisit the WordPress HTTP API to examine other methods such as wp_remote_post and wp_remote_request so that we have a complete understanding of the HTTP API.

Until then, this series will hopefully provide you with the most in-depth introduction possible to wp_remote_get that will not only help you improve your work, but also spark your curiosity about what else is possible with remote requests Heart.

The above is the detailed content of Explore the WordPress HTTP API: Learn about wp_remote_get and its responses. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn