简体   繁体   English

创建一个 cookie 以使用法拉第 GET 请求发送

[英]Creating a cookie to send with faraday GET request

I am trying to trigger a GET request where I need to send two cookies (I obtain these through inspecting my browser cookies once I authenticate into my website) that authorises my request.我正在尝试触发一个 GET 请求,我需要发送两个 cookies(我通过在我的网站上进行身份验证后通过检查我的浏览器 cookies 获得这些)来授权我的请求。 However, when I try the below ruby code using the faraday gem I receive an unauthorised access error, which isn't the case when I use postman to send the same cookie data ( https://learning.postman.com/docs/sending-requests/cookies/ ). However, when I try the below ruby code using the faraday gem I receive an unauthorised access error, which isn't the case when I use postman to send the same cookie data ( https://learning.postman.com/docs/sending -请求/cookies/ )。 Can anyone see what I am doing wrong?谁能看到我做错了什么?

url = "https://someurl.com/random_data"
  resp = Faraday.get(url) do |req|
    req.headers['cookie'] = '{"credential_1":' + @credentials["credential_1"] + ',"credential_2":' + @credentials["credential_2"]}'
  end

The wasn't working due to a misconstructed cookie (needed to be pieced together with a ';').由于 cookie 构造错误(需要用 ';' 拼凑在一起),因此无法正常工作。 By following this answer https://stackoverflow.com/a/42911732/427499 I rewrote the assembly of the cookie to look like the below which now works.通过遵循这个答案https://stackoverflow.com/a/42911732/427499 ,我重写了 cookie 的程序集,使其看起来像下面这样现在可以工作。

url = "https://someurl.com/random_data"
resp = Faraday.get(url) do |req|
  cookie_hash = {"credential_1" => @auth_credentials["credential_1"], "credential_2" => @auth_credentials["credential_2"]}

  req.headers['Cookie'] = cookie_hash.map { |key, value| "#{key}=#{value}" } .join('; ')
end

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

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