2014-06-07 64 views
1

我试图用R来快速缩短一批网址。在谷歌API文档提供了解决方案下面使用curl谷歌API - 与R的URL缩短器

curl https://www.googleapis.com/urlshortener/v1/url \ 
    -H 'Content-Type: application/json' \ 
    -d '{"longUrl": "http://www.google.com/"}' 

我试过,使用R将其转换为R,但我不断收到“错误:错误的请求”。这是我正在与之合作。

library(RCurl) 
library(RJSONIO) 

postForm("https://www.googleapis.com/urlshortener/v1/url" , 
     .params= c(data = '{"longUrl":"www.google.com"}'), 
     .opts = list(httpheader = "Content-Type: application/json", 
        ssl.verifypeer = FALSE)) 
+1

跳过斜杠在您的JSON有更多的运气解析输出。 – Thomas

+0

它适合你吗?如果是这样,你可以发布代码,因为它不断给我同样的错误。 – user1637000

回答

2

下面是使用HTTR作为RCurl的包装的解决方案。

> library("httr") 
> POST('https://www.googleapis.com/urlshortener/v1/url', 
     add_headers("Content-Type"="application/json"), 
     body='{"longUrl": "http://www.google.com/"}') 
Response [https://www.googleapis.com/urlshortener/v1/url] 
    Status: 200 
    Content-type: application/json; charset=UTF-8 
{ 
"kind": "urlshortener#url", 
"id": "http://goo.gl/fbsS", 
"longUrl": "http://www.google.com/" 
}