This article describes how to parse functions related to sending http requests in WordPress, including using functions in the WP_Http class to send post or get requests, for more information about how to send Http requests (GET/POST) in PHP, such as the file_get_contents () function, fopen () function, or cURL extension, however, due to different server situations, it may not be compatible with all situations. Therefore, it is very troublesome to make a series of judgments to send Http requests.
However, WordPress provides a WP_Http class to help you determine the compatibility. you only need to call the functions inside to complete the Http request sending. Below I will briefly introduce the common functions of this class.
Send GET request
/*** Use the WP_Http class to send a simple GET request * 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 key:
- Headers: the returned headers information, which is an array.
- Body: The content of the target, which is the same as that in the browser.
- Response: returned code. if the request is successful, array ('code' => 200, 'message' => 'OK') is returned ')
- Cookies: Cookie information, which is an array
That is to say, the target content is $ result ['body'].
Send POST request
If you need to send a POST request, you need to use the second parameter WP_Http-> request (). The following is an example:
/*** Use the WP_Http class to send a simple POST request * http://www.endskin.com/wp_http/#/?http = new WP_Http; $ post = array ('name' => 'bingo ', 'blog '=> 'http: // www.bgbk.org'); $ result = $ http-> request ('http: // www.endskin.com ', array ('method' => 'post', 'body' => $ POST ));
For the returned $ result variable content, see the above GET request.
POST request to be verified
If you want to submit some information in some RESTFul APIs, you need to verify first. we need to send a base64 encoded string containing the user name and password pair to the API, as shown 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 is added to the WP_Http Class, it gives up the PHP Class Snoopy. Therefore, we recommend that you use WP_Http for HTTP requests when writing plug-ins for WordPress.