简体   繁体   English

请求使用 HTTParty 返回带有标头的 401 Unauthorized

[英]Request returns 401 Unauthorized with headers using HTTParty

i can get response from API using curl like this:我可以像这样使用 curl 从 API 获得响应:

curl -X GET https://myapi.com/... -H "client_id: my_id" -H "client_secret: my_secret" 

but when i send requests with HTTParty:但是当我使用 HTTParty 发送请求时:

response = HTTParty.get(url, headers: {"client_id" => "my_id", "client_secret" => "my_secret"})

the result is:结果是:

#<HTTParty::Response:0x55e5db898160 parsed_response="Unable to retrieve client_id from message", 
@response=#<Net::HTTPUnauthorized 401 Unauthorized readbody=true>, @headers={"cache-control"=>["no-cache"], "pragma"=>["no-cache"], "content-length"=>["41"], "content-type"=>["text/plain"], "expires"=>["-1"], "server"=>["Microsoft-IIS/8.5"], "strict-transport-security"=>["max-age=31536000; includeSubdomains;"], "x-aspnet-version"=>["4.0.30319"], "x-powered-by"=>["ASP.NET"], "access-control-allow-origin"=>["*"], "access-control-allow-credentials"=>["true"], "access-control-allow-headers"=>["*"], "access-control-allow-methods"=>["GET, POST, PUT, DELETE, OPTIONS"], "date"=>["Wed, 13 Apr 2022 08:56:56 GMT"], "connection"=>["close"]}>

and output from response.request is: response.request 中的 output 是:

#<HTTParty::Request:0x000055e5db897120 @changed_hosts=false, @credentials_sent=false, @http_method=Net::HTTP::Get, 
@options={:limit=>5, :assume_utf16_is_big_endian=>true, :default_params=>{}, :follow_redirects=>true, :parser=>HTTParty::Parser, :uri_adapter=>URI, :connection_adapter=>HTTParty::ConnectionAdapter, :headers=>{"client_id"=>"my_id", "client_secret"=>"my_secret"}}, 
@path=#<URI::HTTP http://my_api.com/...>, @last_uri=#<URI::HTTP http://my_api.com/...>, @raw_request=#<Net::HTTP::Get GET>, @last_response=#<Net::HTTPUnauthorized 401 Unauthorized readbody=true>>

my opinion is, the headers goes in @options parameter instead of @headers, so request can't find my client_id.我的意见是,标头进入@options 参数而不是@headers,所以请求找不到我的client_id。 Does anyone know how can i fix this?有谁知道我该如何解决这个问题?

Do not use eval on an API response.不要对 API 响应使用 eval。 Its extremely insecure.它非常不安全。 Use JSON.parse .使用JSON.parse

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM