Home > Article > Backend Development > Analysis of related functions for sending http requests in WordPress, wordpress function_PHP tutorial
There are many methods for sending Http requests (GET / POST) in PHP, such as the file_get_contents() function , fopen() function or cURL extension, but due to different server situations, it may not be compatible with all situations. In this way, sending an HTTP request requires 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 above code stores the request target information in the $result variable. $result is an array with the following keys:
In other words, the content of the target is $result['body']
Send POST request
If you need to send a POST request, you have to use the second parameter of WP_Http->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 returned $result variable content, please refer to the GET request above.
POST request requiring verification
If you want to submit some information to some RESTFul API, you first need to authenticate. 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.