代码之家  ›  专栏  ›  技术社区  ›  Diogo Amaral

实现API请求的正确方式

  •  0
  • Diogo Amaral  · 技术社区  · 1 年前

    我正试图创建一个这样的请求,但使用ruby。

    curl --request POST \
    --url '{BASE_URL}/oauth2/token' \
    --header 'Authorization: Basic {BASIC_CLIENT}' \
    --header 'Content-Type: application/x-www-form-urlencoded' \
    --data grant_type=client_credentials
    

    我试着这样做:

    require 'uri'
    require 'net/http'
    
    url = URI("https://api.userede.com.br/redelabs/oauth2/token")
    http = Net::HTTP.new(url.host, url.port)
    http.use_ssl = true
    
    request = http.post(
      url,
      { 'grant_type' => 'client_credentials' }.to_json,
      { 'Authorization' => "Basic #{CLIENTID}", 'Content-Type' => 'application/x-www-form-urlencoded'}
    )
    

    但我得到了以下错误:

    {\"error_description\":\"OAuth 2.0 Parameter: grant_type\",\"error\":\"invalid_request\",\"error_uri\":\"https://datatracker.ietf.org/doc/html/rfc6749#section-5.2\"}

    1 回复  |  直到 1 年前
        1
  •  2
  •   PaulProgrammer    1 年前

    您将请求格式化为JSON,但系统需要application/x-www-form-urlencoded。

    替换此:

    { 'grant_type' => 'client_credentials' }.to_json,
    

    这样:

    "grant_type=client_credentials",
    

    以符合正确的有效载荷类型。

    这可能不是唯一的错误,但这是一个明显的错误。