繁体   English   中英

HTTP 请求在 Postman 中有效,但在 Ruby 中无效(502 错误)

[英]HTTP request works in Postman but not in Ruby (502 error)

我对 Ruby 很陌生,但必须调试我没有编写的 Ruby 代码。

在 Ruby 代码中,发出了 HTTP 请求。 经过一番记录,我发现响应 object 显示 502 错误。 当我在 Postman 中尝试完全相同的请求时,我得到了预期的成功响应:

在此处输入图像描述

我什至试图从字面上复制/过去 Postman 生成的 Ruby 代码段,当从 Ruby 代码触发时,它仍然给我一个 502 错误。

这里是负责查询的部分(请求方法,post部分):

class PatentApi
  # Patent analysis API wrapper

  require 'uri'
  require 'net/http'

  DEFAULT_ENDPOINT = configatron.patent_api.endpoint.freeze

  # POST /api/v1/graph
  def post_complete_patent_graph(data)
    response = post('graph', data.to_json)
    response
  end

  # Send as POST request
  def post(path, options = {})
    request(:post, path, options)
  end

  # Build the request and return response
  def request(method, path, options)
    url = URI.parse(DEFAULT_ENDPOINT + path)
    Rails.logger.info (url.inspect) # The url looks ok in the logs !
    params = options # After logging, this value is ok
    case method
      when :get
        url.query = URI.encode_www_form(params)
        http = Net::HTTP.new(url.host, url.port)
        request = Net::HTTP::Get.new(url.request_uri)
        request["Accept"] = 'application/json'
        request["Content-Type"] = 'application/json'
        response = http.request(request)
        return response
      when :post
        request = Net::HTTP::Post.new(url, 'Content-Type' => 'application/json')
        request.body = params
        response = Net::HTTP.start(url.host, url.port, :read_timeout => 320) do |http|
          http.request(request)
        end
        Rails.logger.info 'RESPONSE'
        Rails.logger.info (response.code) # 502 ! :(
        Rails.logger.info (response.message)
        Rails.logger.info 'END RESPONSE'
        return response
    end
  end
end

您是否尝试包含Content-Type header 之类的

request = Net::HTTP::Post.new(url)
request["Content-Type"] = "application/json"

暂无
暂无

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

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