我试图用wp_remote_post()缩短谷歌url
但是我得到了错误的结果,
我知道如何使用CURL,但在WordPress中不允许使用CURL!
这个资源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>';
}
如果您想要更改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 . '"}',
);