2014-06-07 65 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/" 
}