【问题标题】:google url shortener api with wp_remote_post带有 wp_remote_post 的谷歌 url 缩短器 api
【发布时间】:2014-12-24 17:25:48
【问题描述】:

我尝试使用 wp_remote_post() 缩短谷歌网址

但我得到了错误结果,

我知道如何使用 CURL,但 WordPress 不允许使用 CURL!


此 WordPress API 资源:

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

【问题讨论】:

    标签: php json wordpress api curl


    【解决方案1】:

    如果您想更改 POST 请求的内容类型,WordPress API 要求 headers 数组包含元素 content-type

    此外,您的 HTTP 请求的 body 似乎是作为 PHP 数组传递的,而不是 Google Shortener API 要求的 JSON 字符串。

    body 的数组定义包装在json_encode 语句中,并使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 . '"}',
    );
    

    【讨论】:

    • 我会努力的,我会告诉你,等我。
    • 不工作!查看此消息:此 API 不支持解析表单编码输入。
    • 根据 WordPress 文档,headers 变量的格式也是错误的。我更新了答案 - 再试一次。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-06-09
    • 2015-10-18
    • 2012-01-09
    • 2023-04-05
    • 2016-02-20
    • 2016-11-26
    • 1970-01-01
    相关资源
    最近更新 更多