Ruby Rest client POST, how to send headers

15.1k Views Asked by At

Ruby rest client is not able to send headers, my java service is not able to read headers when I trigger post request from ruby as below. My Service layers throws error Header companyID is missing. When run the same http request in Postman it works.

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

Here is postman code that works. Need similar in Ruby Rest, pls advise.

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

There are 2 best solutions below

0
Naga On BEST ANSWER

Below worked. Looks like headers should be in same line.

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
0
JayJay On

Try using the RestClient post method:

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

Payload in this instance is a string, so you'll need to figure out the appropriate structure for application/x-www-form-urlencoded. For example:

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