使用 httr 的 POST 请求后内容类型无效

Invalid Content Type after a POST request with httr

我正在尝试使用法国 Public 就业服务中心 (Pôle Emploi) 提供的名为 "Offres d'emploi v2" 的 API(职位空缺)。 API 被描述为 here. Using the API requires a token, and an authentification via OAuth v2, in a process described here

我正在使用 R 3.5.0 和 httr 1.3.1。首先,我指定请求正文。 eeideesec 是我注册时Pôle Emploi 发来的标识符和秘钥。

require(jsonlite)
require(httr)

request_body <- list(
   grant_type = "client_credentials",
   client_id = eeid,
   client_secret = eesec,
   scope = paste(
      "api_offresdemploiv2",
      "o2dsoffre",
      paste0("application_",eeid,"%20api_offresdemploiv2"), sep = " "))

然后,我运行 POST 请求:

result_auth <- POST(
    "https://entreprise.pole-emploi.fr/connexion/oauth2/access_token",
    realm = "/partenaire",
    body = request_body,
    add_headers('Content-Type'='application/x-www-form-urlencoded')
    )
result_auth
content(result_auth)

其中 returns 关于内容类型的错误:

> result_auth
Response [https://entreprise.pole-emploi.fr/connexion/oauth2/access_token]
  Date: 2018-09-29 14:33
  Status: 400
  Content-Type: application/json; charset=UTF-8
  Size: 70 B
> content(result_auth)
$error
[1] "invalid_request"

$error_description
[1] "Invalid Content Type"

我也尝试用 content_type("application/x-www-form-urlencoded") 替换行 add_headers('Content-Type'='application/x-www-form-urlencoded'),但我收到相同的错误消息。

我显然在这里做错了什么,但是什么?谢谢你的帮助。

这是@hrbrmstr 直接评论后的答案。非常感谢他。

不应将内容类型指定为 header,而是应在 POST 函数中使用 encode = "form" 选项。

请注意,eeideesec 是 Pôle Emploi 在注册时提供的标识符和密钥。完整的脚本如下所示。

require(jsonlite)
require(httr)

request_body <- list(
    grant_type = "client_credentials",
    client_id = eeid,
    client_secret = eesec,
    scope = paste(
"api_offresdemploiv2",
"o2dsoffre",
paste0("application_",eeid), sep = " "))

result_auth <- POST(
    "https://entreprise.pole-emploi.fr/connexion/oauth2/access_token",
    query = list(realm = "/partenaire"),
    body = request_body,
    encode = "form"
    )