HTTP.post_form in Ruby with custom headers - ruby-on-rails

Im trying to use Nets/HTTP to use POST and put in a custom user agent. I've typically used open-uri but it cant do POST can it?
I use
resp, data = Net::HTTP.post_form(url, query)
How would I change this to throw custom headers in?
Edit my query is:
query = {'a'=>'b'}

You can try this, for example:
http = Net::HTTP.new('domain.com', 80)
path = '/url'
data = 'form=data&more=values'
headers = {
'Cookie' => cookie,
'Content-Type' => 'application/x-www-form-urlencoded'
}
resp, data = http.post(path, data, headers)

You can't use post_form to do that, but you can do it like this:
uri = URI(url)
req = Net::HTTP::Post.new(uri.path)
req.set_form_data(query)
req['User-Agent'] = 'Some user agent'
res = Net::HTTP.start(uri.hostname, uri.port) do |http|
http.request(req)
end
case res
when Net::HTTPSuccess, Net::HTTPRedirection
# OK
else
res.value
end
(Read the net/http documentation for more info)

I needed to post json to a server with custom headers. Other solutions I looked at didn't work for me. Here was my solution that worked.
uri = URI.parse("http://sample.website.com/api/auth")
params = {'email' => 'someemail#email.com'}
headers = {
'Authorization'=>'foobar',
'Date'=>'Thu, 28 Apr 2016 15:55:01 MDT',
'Content-Type' =>'application/json',
'Accept'=>'application/json'}
http = Net::HTTP.new(uri.host, uri.port)
response = http.post(uri.path, params.to_json, headers)
output = response.body
puts output
Thanks due to Mike Ebert's tumblr:
http://mikeebert.tumblr.com/post/56891815151/posting-json-with-nethttp

require "net/http"
uri = URI.parse('https://your_url.com')
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
http.ca_path='/etc/pki/tls/certs/'
http.ca_file='/etc/pki/tls/certs/YOUR_CERT_CHAIN_FILE'
http.cert = OpenSSL::X509::Certificate.new(File.read("YOUR_CERT)_FILE"))
http.key = OpenSSL::PKey::RSA.new(File.read("YOUR_KEY_FILE"))
#SSLv3 is cracked, and often not allowed
http.ssl_version = :TLSv1_2
#### This is IMPORTANT
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
#Crete the POST request
request = Net::HTTP::Post.new(uri.request_uri)
request.add_field 'X_REMOTE_USER', 'soap_remote_user'
request.add_field 'Accept', '*'
request.add_field 'SOAPAction', 'soap_action'
request.body = request_payload
#Get Response
response = http.request(request)
#Review Response
puts response.body

Related

How to check if image exists in given url or not?

This is the cloudinary link.
http://res.cloudinary.com/dm1hql92i/raw/upload/c_fill,h_200,w_200/%7B%7D
I want to check if the image exists or not in that link with ruby.
You will come to know that by checking Content-Type which is present in HTTP header
Please refer following code snippet.
require 'net/http'
require 'uri'
def image_exists?(url)
url = URI.parse(url)
http = Net::HTTP.start(url.host, url.port)
http.head(url.request_uri)['Content-Type'].start_with? 'image'
end
url = "http://res.cloudinary.com/dm1hql92i/raw/upload/c_fill,h_200,w_200/%7B%7D"
image_exists?(url)
=> true
url = "http://guides.rubyonrails.org/getting_started.html"
image_exists?(url)
=> false
For some reason Ganesh's answer didnt work for me, here is my approach:
def image_exists?(url)
response = {}
uri = URI(url)
Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') do |http|
request = Net::HTTP::Get.new uri
response = http.request request # Net::HTTPResponse object
end
return response.content_type.starts_with?("image")
end

Https request wth user auth rails

curl -u "token:53555" https://url/method
how to send token in Net::Http url, I tried as
uri = URI.parse(url)
http = Net::HTTP.new(uri.host, uri.port)
request = Net::HTTP::Get.new(uri.request_uri,{'token' => '53555'})
response = http.request(request)
But its not working
Try
uri = URI.parse(url + "?token=53555")
http = Net::HTTP.new(uri.host, uri.port)
request = Net::HTTP::Get.new(uri.request_uri)
response = http.request(request)
request['authorization'] = "Token token=#{token}" Set token like this.
You need to add basic_auth to your request object. Like so:
uri = URI.parse(url)
http = Net::HTTP.new(uri.host, uri.port)
request = Net::HTTP::Get.new(uri.request_uri)
request.basic_auth 'token', '53555'
response = http.request(request)
The request.basic_auth 'token', '53555' is the line that adds the basic authentication code.

rails: User Net::Http post json to reply review google app develop api

I want to reply a review from google app.
This is link document: https://developers.google.com/android-publisher/api-ref/reviews/reply
I use Net::HTTP to post data.
my method to reply review
def self.reply_review(package , access_token, review_id, text )
uri = URI("https://www.googleapis.com/androidpublisher/v2/applications/#{package}/reviews/#{review_id}:reply?access_token=#{access_token}")
puts "https://www.googleapis.com/androidpublisher/v2/applications/#{package}/reviews/#{review_id}:reply?access_token=#{access_token}"
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
params = {
"replyText" => text
}
request = Net::HTTP::Post.new(
uri.request_uri,
'Content-Type' => 'application/json'
)
request.body = params.to_json
response = http.request(request)
puts response
puts(response.body)
response
end
but it always response
=> => #<Net::HTTPBadRequest 400 Bad Request readbody=true>
I am sure my data into accurate (packageName, access_token, replyId).
And how to fix this to reply a review use Net::HTTP
I have used this to connect with google Verification API.
require 'openssl'
require 'net/http'
uri =URI.parse("https://www.googleapis.com/androidpublisher/v2/applications/#{package}/reviews/#{review_id}:reply?access_token=#{access_token}")
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_PEER
request = Net::HTTP::Post.new(uri.request_uri,
initheader = {'Content-Type' =>'application/json'})
request.form_data = {"replyText" => text}
response = http.request(request)

Construct NET::HTTP header files

I am required to make an http request with a header similar to the one quoted below.
POST /approval HTTP/1.1
Content-Type:text/xml
Content-Length:569
Host:127.0.0.1
Authorization: WSSE realm="SDP", profile="UsernameToken"
X-WSSE: UsernameToken Username="xxxxxxxxxxxxxxx", PasswordDigest=" xxxxxxxxxxxxxxxx", Nonce=" xxxxxxxxxxxxxx", Created="2012-07-26T11:31:26Z"
X-RequestHeader: request ServiceId="xxxxxxxxxxxxx", TransId=" xxxxxxxxxxxxxxxxxxx" , LinkId="xxxxxxxxxx", FA="xxxxxxxxxx"
Cookie: sessionid=default8fcee064690b45faa9f8f6c7e21c5e5a
Msisdn: 861111111
X-HW-Extension: k1=v1;k2=v2
<ns2:preapprovalrequest xmlns:ns2="http://www.xxxxxxxx.com">
<fromfri>ID:2341305205559/MSISDN</fromfri>
<tofri>ID:2341305205559/MSISDN</tofri>
<message>abc</message>
</ns2:preapprovalrequest>
I have attempted to make the Net::HTTP Ruby 2.2.0 library with something similar to this.
url = 'http://xxx.xxx.xxx.xxx:xx/xxx/xxx/approval'
request_xml = "<?xml version='1.0' encoding='UTF-8'?><ns2:approvalrequest xmlns:ns2='http://www.xxxxxxxx.com'><fromfri></fromfri><tofri></tofri><message></message></ns2:approvalrequest>"
uri = URI(url)
req = Net::HTTP::Post.new(uri.path)
req.content_type = 'text/xml'
req['Authorization']['/']="WSSE"
req['Authorization']['realm']= "xxxxx"
req['Authorization']['profile']="xxxxxxxx"
req['X-WSSE']['/']="UsernameToken"
req['X-WSSE']['Username']=""
req['X-WSSE']['PasswordDigest']=""
req['X-WSSE']['Nonce']=""
req['X-WSSE']['Created']=""
req['X-RequestHeader']['/']="request"
req['X-RequestHeader']['ServiceId']=""
req['X-RequestHeader']['TransId']=""
req['X-RequestHeader']['LinkId']=""
req['X-RequestHeader']['FA']=""
req.body = request_xml
response = Net::HTTP.start(uri.hostname, uri.port) {|http|
http.request(req)
}
result = Hash.from_xml(response.body)
However, this throws errors **NoMethodError: undefined method[]=' for nil:NilClass.on the line**req['Authorization']['/']="WSSE"`.Any idea how to construct a proper header file with multiple fields.
you are operating on an empty hash, either merge into it or assign it properly
require 'net/http'
req = Net::HTTP::Post.new('bla')
req.content_type = 'text/xml'
req['Authorization'] = {
'/' => "WSSE",
'realm' => "xxxxx",
'profile' =>"xxxxxxxx",
}
puts req['Authorization'] # => {"/"=>"WSSE", "realm"=>"xxxxx", "profile"=>"xxxxxxxx"}

Sending a Post request with net/http

I need to send data in JSON to another app which runs on the same computer.
I send request like so (rails 3.2.13 )
data = { //some data hash }
url = URI.parse('http://localhost:6379/api/plans')
resp, data = Net::HTTP.post_form(url, data.to_JSON )
p resp
p data
{ resp: resp, data: data.to_JSON }
But i get Net::HTTPBadResponse (wrong status line: "-ERR unknown command 'POST'"):
How can i solve this problem?
Update 1
Updated my code as #Raja-d suggested
url = URI.parse('http://localhost:6379/v1/sessions')
http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true
resp, data = Net::HTTP.post_form(url, data)
p resp
p data
But i still get error Net::HTTPBadResponse (wrong status line: "-ERR unknown command 'POST'"):
I don't know what your problem is but what about something like this
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
request = Net::HTTP::Post.new(uri.path, {'Content-Type' => 'application/json'})
request.body = data.to_json
response = http.request(request)

Resources