Ruby Rest客户端POST,如何发送标题

时间:2018-02-08 04:27:38

标签: ruby-on-rails ruby rubygems ruby-on-rails-5 ruby-2.0

Ruby rest客户端无法发送头文件,当我从ruby触发post请求时,我的java服务无法读取头文件,如下所示。我的服务图层抛出错误标头companyID缺失。在Postman中运行相同的http请求时,它可以工作。

response = RestClient::Request.new({
      method: :post,
      url: 'https://example.com/submitForm',
      headers:{content_type: 'application/x-www-form-urlencoded',
              companyID:'Company1',
              Authorization:'Basic HELLO1234'},
      payload: { data: str_res}
    }).execute do |response, request, result|
      case response.code
      when 400
        [ :error, JSON.parse(response.to_str) ]
      when 200
        [ :success, JSON.parse(response.to_str) ]
        puts request.headers 
      else
        fail "Invalid response #{response.to_str} received."
      end
    end

这是邮递员代码。需要类似于Ruby Rest,请建议。

POST /submitForm HTTP/1.1
Host: example.com
companyID: Company1
Authorization: Basic HELLO1234
Content-Type: application/x-www-form-urlencoded
Cache-Control: no-cache
Postman-Token: 528cafa1-2b5d-13a1-f227-bfe0171a9437

data=My Own data

2 个答案:

答案 0 :(得分:2)

以下工作。看起来标题应该在同一行。

payloadString = "data=My Own data" 

    response = RestClient::Request.new({
  method: :post,
  url: 'https://example.com/submitForm',
  payload: payloadString,
  headers: {content_type: 'application/x-www-form-urlencoded', companyID:'Company1', Authorization:'Basic HELLO1234'}
   }).execute do |response, request, result|
  case response.code
  when 400
    [ :error, JSON.parse(response.to_str) ]
  when 200
    [ :success, JSON.parse(response.to_str) ]
  else
    fail "Invalid response #{response.to_str} received."
  end
end

答案 1 :(得分:0)

尝试使用RestClient post方法:

result = RestClient.post(
  'https://example.com/submitForm', 
  payload, 
  {
    content_type: 'application/x-www-form-urlencoded', 
    companyID: 'Company1', 
    Authorization: 'Basic HELLO1234'
  }
)

此实例中的有效负载是一个字符串,因此您需要找出application / x-www-form-urlencoded的相应结构。例如:

payload.to_json => '{"data": "str_res"}'