Tags

, , , , , ,

WordPress-HTTP-APIWhat is WordPress HTTP API ?
Do you want to make a request to any remote server to get something or to post something ? WordPress HTTP API is the solution for you. It provides a simple interface to make remote requests. It supports methods such as POST, GET, HEAD, PUT, etc. Below are some of the helper functions it provides.

wp_remote_get() - Retrieves a URL using the GET HTTP method.
wp_remote_post() - Retrieves a URL using the POST HTTP method.
wp_remote_head() - Retrieves a URL using the HEAD HTTP method.
wp_remote_request() - Retrieves a URL using either the default GET or a custom HTTP method.


For more information visit: http://codex.wordpress.org/HTTP_API

Why to use WordPress HTTP API ?
There are several ways to connect and communicate with any remote host from PHP.

  • cURL : A library to communicate with remote hosts.But this works only when the cURL extension is loaded into PHP.
  • File system (fopen, file_get_contents) : This function opens up a file or an URL and this works when php ini_settings allows for this.
  • Sockets (fsockopen) : Initiates a socket connection to the resource specified by host-name. Again it’s possible that the hosting company might have disabled the fsockopen function or firewalled outbound requests on whatever port you’re trying to connect.
  • Streams: Works on PHP 4.3 or later.
  • HTTP: Provides a powerful request and parallel interface for remote calls. It needs PHP 5.2+

If you see all of the above, these methods of remote communication works based upon some conditions/situations/hosting environment/php versions etc. On top of that we as developer need to know/learn lot of things cURL, fopen, fsockopen, php http, php streams etc. So, when we are creating plugins we have to consider all of the above checks before using these. To make sure a call to remote host works, we need to check if things are supported on that particular host and php environment and write code accordingly. WordPress has already done excatly that for us. It does all the checking and use the suitable method that works. If everything fails, then it returns a error(WP_Error).

How to use WordPress HTTP API ?
Lets consider an example of getting exact co-ordinates of a location from Google Maps API.

$address = '142 Montague St, Brooklyn, NY, 11201';
$address = urlencode( $address );
$response = wp_remote_get( "http://maps.googleapis.com/maps/api/geocode/json?address=" . $address . "&sensor=true" );

// check the response status code not to be 404
if ( is_wp_error( $response ) || 200 != wp_remote_retrieve_response_code( $response ) )
    return false;

try {

    // get the response body
    $result = wp_remote_retrieve_body( $response );

    // as the response for Google is in json ( geocode/json?address= )
    $result = json_decode( $result );

} catch ( Exception $ex ) {

    $result = null;

}

if( !empty( $result ) ) {
    $lat = $result->results[0]->geometry->location->lat;
    $lng = $result->results[0]->geometry->location->lng;
}

Description of the above code:
— In the above example Google MAPs API url is being used as the parameter for wp_remote_get()
$response = wp_remote_get( "http://maps.googleapis.com/maps/api/geocode/json?address=" . $address . "&sensor=true" );
— Check whether the response results in an error OR the response from the remote host has error status code.
if ( is_wp_error( $response ) || 200 != wp_remote_retrieve_response_code( $response ) )
— Get the actual response body out of complete response.
$result = wp_remote_retrieve_body( $response );
— Use the response body as you like.
$result = json_decode( $result );
if( !empty( $result ) ) {
$lat = $result->results[0]->geometry->location->lat;
$lng = $result->results[0]->geometry->location->lng;
}

The complete response of the wp_remote_get() looks like this:

Array
(
    [headers] => Array
        (
            [content-type] => application/json; charset=UTF-8
            [date] => Fri, 27 Sep 2013 06:59:35 GMT
            [expires] => Sat, 28 Sep 2013 06:59:35 GMT
            [cache-control] => public, max-age=86400
            [vary] => Accept-Language
            [access-control-allow-origin] => *
            [server] => mafe
            [x-xss-protection] => 1; mode=block
            [x-frame-options] => SAMEORIGIN
            [alternate-protocol] => 80:quic
        )

    [body] => {
       "results" : [
          {
             "address_components" : [
                {
                   "long_name" : "142",
                   "short_name" : "142",
                   "types" : [ "street_number" ]
                },
                {
                   "long_name" : "Montague Street",
                   "short_name" : "Montague St",
                   "types" : [ "route" ]
                },
                {
                   "long_name" : "Brooklyn Heights",
                   "short_name" : "Brooklyn Heights",
                   "types" : [ "neighborhood", "political" ]
                },
                {
                   "long_name" : "Brooklyn",
                   "short_name" : "Brooklyn",
                   "types" : [ "sublocality", "political" ]
                },
                {
                   "long_name" : "Brooklyn",
                   "short_name" : "Brooklyn",
                   "types" : [ "locality", "political" ]
                },
                {
                   "long_name" : "Kings",
                   "short_name" : "Kings",
                   "types" : [ "administrative_area_level_2", "political" ]
                },
                {
                   "long_name" : "New York",
                   "short_name" : "NY",
                   "types" : [ "administrative_area_level_1", "political" ]
                },
                {
                   "long_name" : "United States",
                   "short_name" : "US",
                   "types" : [ "country", "political" ]
                },
                {
                   "long_name" : "11201",
                   "short_name" : "11201",
                   "types" : [ "postal_code" ]
                }
             ],
             "formatted_address" : "142 Montague Street, Brooklyn, NY 11201, USA",
             "geometry" : {
                "location" : {
                   "lat" : 40.6943849,
                   "lng" : -73.99368
                },
                "location_type" : "ROOFTOP",
                "viewport" : {
                   "northeast" : {
                      "lat" : 40.69573388029149,
                      "lng" : -73.99233101970849
                   },
                   "southwest" : {
                      "lat" : 40.69303591970849,
                      "lng" : -73.99502898029151
                   }
                }
             },
             "types" : [ "street_address" ]
          }
       ],
       "status" : "OK"
    }

    [response] => Array
        (
            [ code] => 200
            [message] => OK
        )

    [cookies] => Array
        (
        )

    [filename] =>
)

Conclusion:
If you are a WordPress developer never ever forget to use wp_remote_get() for making remote requests. WordPress HTTP API is the best solution which works irrespective of hosting environment.

WordPress-HTTP-API

Advertisements