Validating URL by making request - ruby-on-rails

In Rails controller, I'd like to validate a user-inputted URL (say, it's in a variable url) by making a request to it, and checking that the response is not 50X. How can I do that?

You can send request from a controller using Net::Http module as follows
uri = URI('http://festivalsherpa.com')
response = Net::HTTP.get_response(uri)
response.to_hash["status"] will return you proper response code

There is one more way
you can do in more meaningful way like:
uri = URI.parse(your_url)
connection = Net::HTTP.new(uri.host)
request = Net::HTTP::Get.new(uri.request_uri) # For post req, you can replace 'Get' by 'Post'
response = connection.request(request)
You can see what is returned:
p response.body
If the response returned is JSON, then you can do
JSON.parse(response.body) #It will give you hash object
You can check the response code/status
p response.code
If you want to handle status codes, then you can handle it through case statements
case response.code
when "200"
<some code>
when "500"
<some code>
end
And so on..

Related

How can I get the value in a hash of the response of POST request on Ruby?

Now, I am working on a project using post request on Ruby.
I could get the response with the code below.
def send_param(param)
uri = URI.parse('https:~~~~~~~~~~~~')
https = Net::HTTP.new(uri.host, 443)
response = https.post(uri.path, param.to_query)
print response.body
end
And response.body looks like something like this
{"result": {"id":1111, "name": John}}
Now, I need to get the value of John above.
it will be something like this.
response["name"]
but I can't get the value as expected.
So I want you to help me, if you can.
Thank you.
You can parse it and fetch the result after it using the dig method.
def send_param(param)
uri = URI.parse('https:~~~~~~~~~~~~')
https = Net::HTTP.new(uri.host, 443)
response = https.post(uri.path, param.to_query)
JSON.parse(response.body)
end
result = send_param({})
result.dig('result', 'name')

Posting to other website's form and getting response with Rails

I am trying to send some params to this website (http://www.degraeve.com/translator.php) and get the response to my rails application. I want to select 'binary' from the radio buttons whose name is 'd' and put just 'a' on the text field whose name is 'w' to be translated.
I am using this action on my controller:
class RoomsController < ApplicationController
require "uri"
require "net/http"
require 'json'
def test
uri = URI.parse("http://www.degraeve.com/translator.php")
header = {'Content-Type': 'text/json'}
params = { d: 'binary', w: 'a' }
# Create the HTTP objects
http = Net::HTTP.new(uri.host, uri.port)
request = Net::HTTP::Post.new(uri.request_uri, header)
request.body = params.to_json
# Send the request
response = http.request(request)
render json: response.body
end
end
Is there something wrong? It just renders the body of http://www.degraeve.com/translator.php before submitting the form, but I would like to get the body after it has been submitted.
When you look at what happens after you press the "Translate!" button you may notice that there is no form being submitted via POST. Instead, a GET request is sent and a HTML file is returned - see for yourself in your browser's network inspector.
Consequently, you can send a simple GET request with a prepared URL, like this (note the d and w query parameters):
uri = URI.parse("http://www.degraeve.com/cgi-bin/babel.cgi?d=binary&url=http%3A%2F%2Fwww.multivax.com%2Flast_question.html&w=a")
response = Net::HTTP.get_print(uri)
and then parse the response accordingly.

RSpec tests for RestClient::Request.execute: Any way to see the request?

I am using RestClient gem to build an API client and the calls to the API are processed by this method here
def call(api_name,api_endpoint,token = nil,*extra_params)
endpoint = fetch_endpoint(api_name,api_endpoint)
params = {}
endpoint['params'].each_with_index { |p,i| params[p] = endpoint['values'][i] }
puts params
if token.nil? then
response = RestClient::Request.execute(method: endpoint['method'], url: endpoint['url'], params: params.to_json)
else
response = RestClient::Request.execute(method: endpoint['method'], url: endpoint['url'], headers: {"Authorization" => "Bearer #{token}"}, params: params.to_json)
end
response
end
As you may see, all I do is mounting a hash with parameters/values for the call and invoking RestClient::Request#execute to get a response.
It happens that some of my tests, like this one
it 'request_autorization' do
obj = SpotifyIntegration.new
response = obj.call('spotify','request_authorization',nil,state: obj.random_state_string)
myjson = JSON.parse(response.body)
expect(myjson).to eq({})
end
are returning a 400 Bad request error, and I really don't know why. Other tests, like this one
it 'my_playlists (with no authorization token)' do
obj = SpotifyIntegration.new
expect {
response = obj.call('spotify','my_playlists')
}.to raise_error(RestClient::Unauthorized,'401 Unauthorized')
end
processed by the same method, run perfectly fine.
Is there any way to see the request sent? I mean, see how RestClient is mount/sending my request to the corresponding API? May be this way I could understand what is happening.
By "see the request" I mean something like
puts RestClient::Request.prepared_request
or
puts RestClient::Request.prepared_url
I've searched the RestClient documentation and found nothing similar, but maybe some of you know how to do this.
You might try using RestClient.log to get more information. Something like:
RestClient.log = STDOUT
WebMock is also a great test framework for HTTP requests. The tests for rest-client itself make a lot of use of WebMock.

http request and get a json for response in rails

In a rails project, I want send a http request and get a json in response and save it to database. I send http request like below:
def test_json
#url is a address like: http://192.32.10.18:8080/GetJson?serial=4306341
uri = URI.parse(url)
response = Net::HTTP.get_response(uri)
end
Now, I want save this json to database and then show to user, How can I do this?
To get the response body you'd use:
uri = URI.parse(the_url)
response = Net::HTTP.get_response(uri)
At this point response is your response (in your case its a string of JSON) which you can do whatever you want with.

Ruby can't read POST header information

I'm creating a post to send to a RESTful web service, my current code looks as such:
vReq = Net::HTTP::Post.new(uri.path)
vReq.body = postData
vReq.basic_auth('user', 'pass')
#printReq = vReq['basic_auth']
I am finding that the #printReq does not get assigned anything, and the headers, is not defined. Attempting to read any known header by name returns no results. It appears no header information is getting created when I do this. vReq.body does in fact return the postData I've created. What am I missing that will create the headers correctly?
You might want to try something like this:
domain = 'example.com'
path = '/api/action'
http = Net::HTTP.new(domain)
http.start do |http|
req = Net::HTTP::Post.new(path)
req.basic_auth 'user', 'pass'
req.set_form_data(postData, ';')
response = http.request(req)
puts response.body # Get response body
puts response.header["content-encoding"] # Get response header
end

Resources