【发布时间】:2014-10-09 03:36:54
【问题描述】:
我正在尝试使用 Google API 缩短数千个 URL。我正在使用 httr 进行 POST。每当我提供作为变量发布的 URL 时,我都会收到“客户端错误:(400) 错误请求”,但是当直接以字符串形式提供相同的 URL(例如“http://www.google.com”)时,一切正常。下面提供了一个最小的示例:
library(httr)
library(httpuv)
# enter data
mydata <- data.frame(Link = "http://www.google.com")
# 1. Find OAuth settings for google:
# https://developers.google.com/accounts/docs/OAuth2InstalledApp
oauth_endpoints("google")
# 2. Register an application at https://cloud.google.com/console#/project
myapp <- oauth_app("google", key = "key goes here", secret = "secret goes here")
# 3. Get OAuth credentials
google_token <- oauth2.0_token(oauth_endpoints("google"), myapp, scope = "https://www.googleapis.com/auth/urlshortener")
这会返回错误:客户端错误:(400) 错误请求
req <- POST('https://www.googleapis.com/urlshortener/v1/url?fields=id',
add_headers("Content-Type"="application/json"),
body='{"longUrl": mydata$Link[1]}', config(token = google_token))
stop_for_status(req)
这很好用
req <- POST('https://www.googleapis.com/urlshortener/v1/url?fields=id',
add_headers("Content-Type"="application/json"),
body='{"longUrl": "http://www.google.com"}', config(token = google_token))
stop_for_status(req)
我尝试对 URL 进行编码,同时测试了 http 和 https,但上述方法似乎都没有任何效果。谁能给我任何建议?提前谢谢!
-杰克
【问题讨论】:
标签: r google-api httr google-url-shortener