2014-10-29 101 views
2

我試圖讓谷歌URL縮短與wp_remote_post()谷歌URL縮短API與wp_remote_post

,但我得到錯誤結果,

我知道如何使用捲曲,但在WordPress捲曲不允許的!


這個資源,API與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


這谷歌網址縮短服務API文檔:

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


這是我的代碼:

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>'; 
} 

回答

2

WordPress的API要求headers數組包含的元素content-type,如果你想更改POST請求的內容類型。

此外,它看起來像您的HTTP請求的body正在作爲PHP數組傳遞,而不是像Google Shortener API那樣需要的JSON字符串。

裹在json_encode語句body數組定義,使headers領域的子陣列,並給它一個鏡頭:自己

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

替代,你可以只寫JSON格式,因爲它很簡單:

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

我會盡力而且我會告訴你,等我。 – user3492381 2014-10-29 05:25:06

+0

不工作! 尋找這個messsage: 這個API不支持解析表單編碼的輸入。 – user3492381 2014-10-29 05:28:59

+0

根據WordPress文檔,'headers'變量的格式也是錯誤的。我更新了我的答案 - 再試一次。 – Manmaru 2014-10-29 05:42:08