2

I need to POST to an API, which requires a header in the request called "Timestamp", whose value has to be an integer (current time from epoch as an integer).

I tried to do this with HTTParty and with Net::HTTP as follows:

response = HTTParty.post(route, body: options[:body].to_json,headers: { 'Timestamp' => Time.now.to_i, 'Authorization' => "Bearer #{options[:token]}",'Content-Type' => 'application/json' })
# >> NoMethodError: undefined method `strip' for 1522273989:Integer

It calls strip on the header value, which throws an error because you can't call strip on an integer.

Does anyone have any idea how I can pass an integer in the request headers?

sawa
  • 165,429
  • 45
  • 277
  • 381
Steve Q
  • 395
  • 5
  • 28
  • could you give a more complete stack trace? It is hard to deduce much from just the error line. – Sean Mar 28 '18 at 21:56
  • 2
    Your problem is merely syntactical. `Time.now.to_i.to_s` will do the trick. – Josh Brody Mar 28 '18 at 22:01
  • @Sean there's nothing else to the stack trace. It's not my API so I don't see what's happening on the other end all I get back is # – Steve Q Mar 28 '18 at 22:08
  • @JoshBrody I tried .to_s but unfortunately no luck. If do that they hit me back with an error saying "Replay attack detected" it has to be an integer not a string – Steve Q Mar 28 '18 at 22:09
  • 2
    You can't send an integer in a header. https://tools.ietf.org/html/rfc7230#section-3.2 – max Mar 28 '18 at 22:10

1 Answers1

2

Call .to_s on the integer:

response = HTTParty.post(route, body: options[:body].to_json,headers: { 'Timestamp' => Time.now.to_i.to_s, 'Authorization' => "Bearer #{options[:token]}",'Content-Type' => 'application/json' })

You can't really send an integer in a header - its the server on the receiving end that must convert the plaintext headers from the request.

Header fields are colon-separated name-value pairs in clear-text string format, terminated by a carriage return (CR) and line feed (LF) character sequence.
List of HTTP header fields - Wikipedia

max
  • 96,212
  • 14
  • 104
  • 165
  • I tried .to_s but unfortunately no luck. If do that they hit me back with an error saying "Replay attack detected" it has to be an integer not a string It's good to know it's not just me that it seemed weird to. I'll have to reach out to the API developer and see if they can change it or handle the conversion on their end – Steve Q Mar 28 '18 at 22:10
  • 1
    They have to handle conversion on their end - HTTP headers are defined by the IETF as a plaintext format. Its just not possible to do it any other way. You can't put a poodle in a fax machine and expect to get anything else than a piece of paper out in the other end. – max Mar 28 '18 at 22:22
  • haha thanks I asked them about it. I'll accept the answer because there's no other way around it. – Steve Q Mar 29 '18 at 01:11