如何使用R使用Google Translate API进行POST调用

时间:2018-06-10 15:10:48

标签: r google-cloud-platform google-translate httr google-translation-api

if (!require("httr")) {
  install.packages("httr", repos="http://cran.rstudio.com/")
  library("httr")
}

if (!require("jsonlite")) {
  install.packages("jsonlite", repos="http://cran.rstudio.com/")
  library("jsonlite")
}

我的工作正常......

api <- "xxxxxxxxxxxxxxxx"
url <-paste0(
   "https://translation.googleapis.com/language/translate/v2/languages/? 
   key=",api
 )
data3 <- GET(url)
data3 <- content(data3)
data3 <- as.data.frame(data3)
data3 <- as.data.frame(t(data3))

我的POST不起作用

url <- paste0(
   "https://translation.googleapis.com/language/translate/v2/detect/?key=",api
 )
request_body <- data.frame(message = "hello")
request_body_json <- toJSON(list(documents = request_body), auto_unbox = TRUE)
result <- POST(url, body = request_body_json)

我试图让语言检测工作 我的理解是我们需要在JSON文件中发布google API 但是我收到了错误     #&#34;代码&#34;:400,     #&#34; message&#34;:&#34;必填文字&#34;

我希望有人可以指出我正确的方向 我知道有一个R包,但我试图学习如何不用 该软件包,因为有时google或microsoft会更新他们的API,#package也不会更新(例如:自从API更新以来,TranslateR并不支持Microsoft,所以我想学习如何手动执行此操作#as as可能 https://cloud.google.com/translate/docs/quickstart?csw=1 https://translation.googleapis.com/ $发现/休息?版本= V2

1 个答案:

答案 0 :(得分:1)

没关系......经过几个小时的黑客攻击后我想出来了.. =)

TEXT1 = "Testate con lo smartphone si sente decisamente bene"
TEXT1 <- str_replace_all(TEXT1, " ", "%20")
test1 <- paste0("https://translation.googleapis.com/language/translate/v2?target=en&key=xxxxxxxxx&q=", TEXT1)
result2 <- POST(test1)
result2 <- content(result2)
result2 <- as.data.frame(result2)