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

3

Ruby的rest客户端无法发送标头,当我使用如下方式从Ruby触发POST请求时,我的Java服务无法读取标头。我的服务层会抛出错误,指出Header 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

这是可用的Postman代码。需要类似的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

应该是 CompanyID 吗?你写的是 companyID(看起来可能区分大小写)。 - Taryn East
1
那只是问题中的一个笔误,已经更正了。仍需要帮助。 - Naga
2个回答

8
以下的内容可以正常工作。看起来,标题应该在同一行上。
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
尝试使用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"}'

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接