简体   繁体   中英

Ruby Rest client POST, how to send headers

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

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

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"}'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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