使用ruby将RestClient请求转换为Net :: HTTP

时间:2018-11-05 10:01:00

标签: ruby-on-rails ruby rest-client net-http

将RestClient请求转换为Net :: HTTP时遇到麻烦。

功能1:

payload = {'login': 'user', 'password': 'pass'}
headers = {'Shopify-Auth-Mechanisms': 'password'}
headers['Host'] = 'https://sample.com'
headers['User-Agent'] = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_3) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.57 Safari/537.17'

uri = URI('https://login.com/test')

response = RestClient.post(url, payload, headers) do |response, request, result, &block|
  puts response.code
  if [301, 302, 307].include? response.code
    @cookies = response.cookies
    RestClient.get(response.headers[:location], cookies: @cookies)
  else
    response.return!(request, result, &block)
  end
end

page = Nokogiri::HTML(response)
@crsf_token = page.css("meta[name='csrf-token']").first.attributes["content"].value

功能2:

response = RestClient::Request.execute(
  method: :post,
  payload: sample_data.to_json,
  url: @discount_url,
  cookies: @cookies,
  headers: headers
)

在功能1:中,我尝试使用以下代码,但结果不同。

#try 1

uri = URI(@login_url)
Net::HTTP.start(uri.host, uri.port) do |http, payload, &block|
  request = Net::HTTP::Post.new(uri.request_uri, headers)
  request.body = payload.to_json
  response = http.request(request)

  puts response.code
end 

#try 2

uri = URI(@login_url)
http = Net::HTTP.new(uri.host, uri.port)
request = Net::HTTP::Post.new(uri.request_uri)
request["Shopify-Auth-Mechanisms"] = 'password'
request["Host"] = 'https://sample.com'
request["User-Agent"] = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_3) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.57 Safari/537.17'
request.body = payload.to_json
request.basic_auth(username, password)
response = http.request(request)

在原始的RestClient请求(功能1)中返回200 ,但在我的转换中,返回 400

对此没有太多想法,请帮助转换2个函数。预先谢谢你!

0 个答案:

没有答案