【问题标题】:Google API - URL Shortener with RGoogle API - 使用 R 的 URL 缩短器
【发布时间】:2014-06-07 13:59:36
【问题描述】:

我正在尝试使用 R 快速缩短一批 URL。 google API 文档使用 curl 提供了以下解决方案

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))

【问题讨论】:

  • 跳过 json 中的斜杠。
  • 它对你有用吗?如果是这样,您可以发布代码,因为它一直给我同样的错误。

标签: r api curl rcurl


【解决方案1】:

这是一个使用 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/"
}

【讨论】:

    【解决方案2】:

    根据https://stackoverflow.com/questions/12302941/convert-curl-code-into-r-via-the-rcurl-package 的建议,在使用 Rcurl+JSONIO 时,我有更多的运气来解析输出

    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))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多