Home > Article > Backend Development > Analysis of related functions for sending http requests in WordPress
There are many ways to send Http requests (GET / POST) in PHP, such as file_get_contents() function, fopen() function or cURL extension. However, due to different server conditions, they may not be compatible with all situations. If you want to send Http requests need to go through a series of judgments, which is very troublesome.
However, WordPress provides a WP_Http class to help you determine compatibility. You only need to call the function inside to complete sending Http requests. Below I will briefly introduce the commonly used functions of this class.
Send GET request
/** *使用 WP_Http 类发送简单的 GET 请求 *http://www.endskin.com/wp_http/ */ $http = new WP_Http; $result = $http->request( 'http://www.endskin.com' );
The code above stores the request target information in the $result variable. $result is an array with the following keys:
That is to say, the content of the target is $result['body']
Send a POST request
If you need to send a POST request, you must use WP_Http-> The second parameter of request(), see the example below:
/** *使用 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 ) );
For the content of the $result variable returned, please refer to the GET request above.
POST request that requires verification
If you want to submit some information to some RESTFul API, you need to verify it first. We need to send a base64-encoded string containing a username and password pair to the API, as detailed below:
// 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 ) );
After WordPress added the WP_Http class, it abandoned the Snoopy PHP Class. Therefore, it is recommended that when writing plug-ins for WordPress, try to use WP_Http to make HTTP requests.
The above introduces the analysis of related functions to implement sending http requests in WordPress, including the relevant content. I hope it will be helpful to friends who are interested in PHP tutorials.