1

I'm attempting to use R to shorten a batch of URLs quickly. The google API documentation provides the solution below using curl

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

I tried converting it to R using R, but I keep getting "Error: Bad Request". Here is what I'm working with.

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))
user1637000
  • 152
  • 4
  • 14

2 Answers2

2

Here's a solution using httr as a wrapper for 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/"
}
Thomas
  • 43,637
  • 12
  • 109
  • 140
0

I had more luck parsing outputs when using Rcurl+JSONIO as per suggestion from https://stackoverflow.com/questions/12302941/convert-curl-code-into-r-via-the-rcurl-package

library(RCurl)
library(RJSONIO)
test <- postForm("https://www.googleapis.com/urlshortener/v1/url",
                 .opts = list(postfields = toJSON(list(longUrl = "http://www.google.com/")),
                 httpheader = c('Content-Type' = 'application/json', Accept = 'application/json'),
                 ssl.verifypeer = FALSE))
Community
  • 1
  • 1