2014-10-29 63 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