user3492381
user3492381

Reputation: 167

google url shortener api with wp_remote_post

I try to make google url shortener with wp_remote_post()

but I got error result,

I know how to use CURL, but CURL not allowed in WordPress!


This resource for API with WordPress:

http://codex.wordpress.org/Function_Reference/wp_remote_post

http://codex.wordpress.org/Function_Reference/wp_remote_retrieve_body

http://codex.wordpress.org/HTTP_API#Other_Arguments

http://codex.wordpress.org/Function_Reference/wp_remote_post#Related


This google url shortener API docs:

https://developers.google.com/url-shortener/v1/getting_started#shorten


This is my code:

function google_url_shrt{
    $url = 'http://example-long-url.com/example-long-url'; // long url to short it
    $args = array(
            "headers"   =>  array( "Content-type:application/json" ),
            "body"      =>  array( "longUrl" => $url )
        );

    $short = wp_remote_post("https://www.googleapis.com/urlshortener/v1/url", $args);
    $retrieve = wp_remote_retrieve_body( $short );
    $response = json_decode($retrieve, true);

    echo '<pre>';
    print_r($response);
    echo '</pre>';
}

Upvotes: 2

Views: 784

Answers (1)

Manmaru
Manmaru

Reputation: 578

The WordPress API requires that the headers array contain an element content-type if you want to change the content type of a POST request.

Also, it looks like the body of your HTTP request is being passed as a PHP array, not as a JSON string as the Google Shortener API requires.

Wrap the array definition for body in a json_encode statement, and make the headers field a sub-array, and give it a shot:

$args = array(
    'headers' =>  array('content-type' => 'application/json'),
    'body'    =>  json_encode(array('longUrl' => $url)),
);

Alternative, you could just write the JSON format yourself as it is fairly simple:

$args = array(
    'headers' =>  array('content-type' => 'application/json'),
    'body'    =>  '{"longUrl":"' .  $url . '"}',
);

Upvotes: 2

Related Questions