【问题标题】:Cannot make request from GET in R to idealista API无法从 R 中的 GET 向 Idealista API 发出请求
【发布时间】:2017-11-27 05:09:00
【问题描述】:

我正在尝试从“idealista”(link) 的 API 发出请求。

它需要身份验证,所以我做的是下一个:

if(!require("jsonlite")){install.packages("jsonlite")}
if(!require("httr")){install.packages("httr")}

consumer_key <- "my_key"
consumer_secret <- "my_secret"

#Use basic auth
secret <- jsonlite::base64_enc(paste(consumer_key, consumer_secret, sep = ":"))
req <- httr::POST("https://api.idealista.com/oauth/token",
                  httr::add_headers(
                    "Authorization" = paste("Basic", gsub("\n", "", secret)),
                    "Content-Type" = "application/x-www-form-urlencoded;charset=UTF-8"
                  ),
                  body = "grant_type=client_credentials"
)


#Extract the access token
token <- paste("Bearer", jsonlite::base64_enc(httr::content(req)$access_token))

所以,首先:我不知道令牌是否必须是 base64 编码(我认为是的)。我做了以下请求:

url<-"https://api.idealista.com/3.5/es/search?locale=es&maxItems=20&numPage=1&operation=sale&order=publicationDate&propertyType=garages&apikey=my_key&t=1&language=es&bankOffer=true" #an example of url (needs apikey)
req <- httr::GET(url, httr::add_headers("Authorization" = token))

响应是:

Response [https://api.idealista.com/3.5/es/search?locale=es&maxItems=20&numPage=1&operation=sale&order=publicationDate&propertyType=garages&apikey=80gzxznozajnl3tf30ite86k1p24e4yb&t=1&language=es&bankOffer=true]
  Date: 2017-10-10 15:25
  Status: 400
  Content-Type: text/html
  Size: 4.4 kB
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/T...
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="es_ES" lang="es_ES">
<head>

                <title>idealista.com : pisos madrid, pisos barcelona, pisos v...
                <meta http-equiv="content-Type" content="text/html; charset=I...
                <meta http-equiv="Expires" content="0"/>
                <meta name="Pragma" content="no-cache"/>
                <meta http-equiv="pragma" content="no-cache"/>
                <meta http-equiv="cache-control" content="no-cache, mustreval...
...

这没有意义。你能告诉我我做错了什么吗? 我收到的状态码是“400”,我不知道我必须做什么。

提前致谢。

【问题讨论】:

  • 这似乎完全特定于 Idealista.com API。您可能应该联系他们寻求支持。或者至少提供其 API 文档相关部分的链接。您真的要添加两个 Authorization 标头吗?

标签: r httr


【解决方案1】:

我在python中发现了一个类似的问题,并在这个link中解决了

第一部分(身份验证)没问题,但第二部分错误。此外,我也尝试了其他 url,并且令牌不需要 base64 编码。

token <- paste("Bearer", httr::content(req)$access_token)

url<-"http://api.idealista.com/3.5/es/search?center=40.42938099999995,-3.7097526269835726&country=es&maxItems=50&numPage=1&distance=452&propertyType=homes&operation=sale"
req <- httr::POST(url, httr::add_headers("Authorization" = token))

如您所见,我使用的是函数“GET”,但是查看上面提到的python代码,我使用了“POST”并且它起作用了!。

我不知道为什么在发出请求时使用 POST 函数,但 API 是这样工作的。

【讨论】:

    猜你喜欢
    • 2019-11-11
    • 1970-01-01
    • 1970-01-01
    • 2021-10-25
    • 1970-01-01
    • 2014-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多