从R调用API以检索数据

时间:2017-10-17 13:58:30

标签: r api curl

我正在尝试从API获取信息。我有Curl声明,但遗憾的是Curl转换器现在不支持R. 我的卷曲声明是:

   curl -X GET "http://192.168.26.71:8080/recommender/containing/?
   lat=5.010880470275879&lon=47.293949127197266&floor=0" -H "accept: 
   application/json"

我正在尝试下面提到的代码;

 library(RCurl)
 library(RJSONIO)
 postForm("http://192.168.26.71:8080/recommender/containing/",
 .opts = list(postfields = toJSON(list('lat' = "5.010880470275879", 
 'lon' = "47.293949127197266", 'floor' = "0" )),
 httpheader = c('Content-Type' = 'application/json', Accept = 
 'application/json'),
 ssl.verifypeer = FALSE))

但它给我一个错误;

 Error: Not Found
 *   Trying 192.168.26.71...
 * Connected to 192.168.26.71 (192.168.26.71) port 8080 (#0)
 > POST /recommender/containing/ HTTP/1.1
 Host: 192.168.26.71:8080
 Content-Type: application/json
 Accept: application/json
 Content-Length: 75

 * upload completely sent off: 75 out of 75 bytes
 < HTTP/1.1 404 Not Found
 < Date: Tue, 17 Oct 2017 14:24:14 GMT
 < Access-Control-Allow-Origin: *
 < Access-Control-Request-Method: GET, PUT, POST, DELETE
 < Access-Control-Allow-Headers: Location, Cache-Control, Pragma, Origin, 
 Authorization, Content-Type, X-Requested-With
 < Access-Control-Expose-Headers: Location, Cache-Control, Pragma, Origin, 
 Authorization, Content-Type, X-Requested-With
 < Content-Type: application/json
 < Transfer-Encoding: chunked
 < Server: Jetty(9.3.8.v20160314)
 < 
 * Connection #0 to host 192.168.26.71 left intact
  Error: Not Found

任何人都可以帮助我吗?谢谢:))

1 个答案:

答案 0 :(得分:0)

好吧,您的命令行请求会发出GET,但您的Rcurl代码会调用postForm这是一个POST请求。那些永远不会是一样的。更类似的呼叫将是

my_url <- "http://192.168.26.71:8080/recommender/containing/?lat=5.010880470275879&lon=47.293949127197266&floor=0"
getURL(my_url,
   httpheader = c(Accept = 'application/json'),
   ssl.verifypeer = FALSE)

RCurl pacakge似乎并没有帮助构建网址。 urltools::param_set()函数可能对此有所帮助。虽然现在更受欢迎的用于发出http请求的pacakge是httr。您的请求看起来像这样

library(httr)
GET("http://192.168.26.71:8080/recommender/containing/", 
  query = list('lat' = "5.010880470275879", 
    'lon' = "47.293949127197266", 
    'floor' = "0" ),
  add_headers(Accept = "application/json"))