Creating an HTTP POST Request with Header info using Net::HTTP in Ruby - ruby

Im trying to programmatically post to an html form on the internet.I have managed to create a request with parameters in the request body but I can't figure out how to pass in Http Header attributes using the Net::Http library. Any ideas if this is possible?... Any other library that would do it for me ?
res = Net::HTTP.post_form(URI.parse('http://test.com/add_comment'),
{'static'=>'1', 'entry_id'=>'23942',})

check out http://snippets.dzone.com/posts/show/6727
especially lines like:
req = Net::HTTP::Get.new(url.path)
req.add_field("X-Forwarded-For", "0.0.0.0")

Related

How to get Headers from request?

I am trying to create a webhook. I am brand new to Ruby, but am setting up a very simple practice server. Each time a new issue/ticket is created for one of my github repos, a POST request is made to a URL that I have setup to grab the payload. I am loosely following this tutorial.
I am able to access all the elements that are being posted in the actual payload/body using this code:
require 'sinatra'
require 'json'
post '/payload' do
request.body.rewind
payload_body = request.body.read
puts payload_body
How can I grab the contents of the header? I have been scrolling through documentation, but have had no luck. I tried accessing the header through response and request.headers and received this error: NoMethodError - undefined method `headers' for #<Sinatra::Request:0x0000000006de49e0>
Please let me know if I am missing something here. Thank you.
Here is an example of the headers from my POST request:
Request URL: http://505db39aa8ef.ngrok.io:
Request method: POST
Accept: */*
content-type: application/json
User-Agent: GitHub-Hookshot/cf3e7e0
X-GitHub-Delivery: 8d7fe080-ecc2-11ea-9b34-d35efaaf3885
X-GitHub-Event: issues
X-GitHub-Hook-ID: 245792914
X-GitHub-Hook-Installation-Target-ID: 279687508
X-GitHub-Hook-Installation-Target-Type: repository
X-Hub-Signature: sha1=ed12f9e7a31b08f9109557d6a9dd899ca85de9b5
request.get_header('HTTP_X_GITHUB_HOOK_INSTALLATION_TARGET_TYPE')
# or
request.env['HTTP_X_GITHUB_HOOK_INSTALLATION_TARGET_TYPE']
It is worth mentioning that,sinatra will process custom header:
add prefix HTTP_
capitalize every letter
gsub - to _
You can use request.env to access all headers.
For detail information about what variable will be added HTTP_ you can refer there

Pass parameters in RestClient post request

I want to send parameters with a POST request using the RestClient gem (but I don't want to pass the params as JSON).
In a GET request, I would have:
url = "http://example.com?param1=foo&param2=bar"
RestClient.get url
How can I pass the same params but in a POST request without passing a JSON ?
Read ReadMe file of Rest-client git, it has lots of examples showing different types of request.
For your answer, try :
url = "http://example.com"
RestClient.post url,:param1=>foo, :param2=>bar

Output Net::HTTP request to human readable form

I am trying to debug a request that I am making to a server, but I can't figure out what is wrong with it, as it seems to be just like the request that I am putting through on RESTClient.
I am initializing it like so:
request = Net::HTTP::Post.new(url.to_s)
request.add_field "HeaderKey", "HeaderValue"
request.body = requestBody
and then I am executing it like so:
Net::HTTP.start(url.host, url.port) do |http|
response = http.request(request)
end
The requestBody is a string that is encoded with Base64.encode64.
Is there a way to output the request to see exactly where it's going and with what contents? I've used Paros for checking my iOS connections and I can also output a description of requests from most platforms I've worked with, but I can't figure it out for Ruby.
I've found that HTTP Scoop works pretty well for grabbing network traffic (disclaimer - it's not free!)

Parse body of POST reqest in self-made server in Ruby

I am writing mock Ruby servers to test components of API. I send a POST request with a body, and I'd like my mock server to return a body of that POST request. Currently i have this code:
require 'socket'
webserver = TCPServer.new('127.0.0.1', 7125)
loop do
session = webserver.accept
session.print "HTTP/1.1 200/OK\r\nContent-type:text/html\r\n\r\n"
request = session.gets
session.puts request
session.close
end
A POST request with body FOO returns a response with body that contains only POST / HTTP/1.1 How to fix it?
Writing your own HTTP server is really going to get you into trouble because the specification, while superficially simple, has a number of subtle nuances that can trip you up. In this case, you're reading one line with gets and ignoring the bulk of the submission. You're going to have to address that by reading in and properly decoding the posted data.
For something with a familiar interface you might start with Net::HTTP::Server instead.

Post request with body_stream and parameters

I'm building some kind of proxy.
When I call some url in a rack application, I forward that request to an other url.
The request I forward is a POST with a file and some parameters.
I want to add more parameters.
But the file can be quite big. So I send it with Net::HTTP#body_stream instead of Net::HTTP#body.
I get my request as a Rack::Request object and I create my Net::HTTP object with that.
req = Net::HTTP::Post.new(request.path_info)
req.body_stream = request.body
req.content_type = request.content_type
req.content_length = request.content_length
http = Net::HTTP.new(#host, #port)
res = http.request(req)
I've tried several ways to add the proxy's parameters. But it seems nothing in Net::HTTP allows to add parameters to a body_stream request, only to a body one.
Is there a simpler way to proxy a rack request like that ? Or a clean way to add my parameters to my request ?
Well.. as i see it, this is a normal behaviour. I'll explain why. If you only have access to a Rack::Request,(i guess that) your middleware does not parse the response (you do not include something like ActionController::ParamsParser), so you don't have access to a hash of parameters, but to a StringIo. This StringIO corresponds to a stream like:
Content-Type: multipart/form-data; boundary=AaB03x
--AaB03x
Content-Disposition: form-data; name="param1"
value1
--AaB03x
Content-Disposition: form-data; name="files"; filename="file1.txt"
Content-Type: text/plain
... contents of file1.txt ...
--AaB03x--
What you are trying to do with the Net::HTTP class is to: (1). parse the request into a hash of parameters; (2). merge the parameters hash with your own parameters; (3). recreate the request. The problem is that Net::HTTP library can't do (1), since it is a client library, not a server one.
Therefore, you can not escape parsing some how your request before adding the new parameters.
Possible solutions:
Insert ActionController::ParamsParser before your middleware. After that, you may use the excellent rest-client lib to do something like:
RestClient.post ('http://your_server' + request.path_info), :params => params.merge(your_params)
You can attempt to make a wrapper on the StringIO object, and add, at the end of stream,your own parameters. However, this is not trivial nor advisable.
Might be one year too late, but I had the same issue verifying Paypal IPNs. I wanted to forward back the IPN request to Paypal for verification but needed to add :cmd => '_notify-validate'.
Instead of modifying the body stream, or body, I appended it as part of the URL path, like so:
reply_request = Net::HTTP::Post.new(url.path + '?cmd=_notify-validate')
It seems a bit of a hack, but I think it's worth it if you aren't going to use it for anything else.

Resources