


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:
- The first index contains
no-cache
whether it has been set - The second index contains information about whether the data has been cached. Simply put, if the
post-check
andpre-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!

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python are both high-level programming languages that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values and handle functions that may return null values.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version
Useful JavaScript development tools