Posting to other website's form and getting response with Rails - ruby-on-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.

Related

How can I parse subpages of another website in Rails?

I'm creating a third-party web application of Last.fm and I'm having an issue with getting info about certain artist from them.
I have a method that parses data about some #{artist} from JSON:
artists_helper.rb
require 'net/http'
require 'json'
module ArtistsHelper
def about(artist)
artist = "?"
url = "http://ws.audioscrobbler.com/2.0/?method=artist.getinfo&artist=#{artist}&api_key=f5cb791cfb2ade77749afcc97b5590c8&format=json"
uri = URI(url)
response = Net::HTTP.get(uri)
JSON.parse(response)
end
end
If I change '?' to the artist name in that method I can successfully parse info about artist from JSON file of that artist. But for when I go the page e.g. http://localhost:3000/artists/Wild+Nothing I need the method 'about(artist)' to get the value 'Wild+Nothing' and parse the data for Wild Nothing from Last.fm's JSON file.
How can I tell the method 'about' that what stands after http://localhost:3000/artists/ is the required value?
In the routes, have a get route name that accepts a variable
get 'artists/:name', to: 'artists#about'
In the artists controller, have an about function:
def about
artist = params[:name]
url = "http://ws.audioscrobbler.com/2.0/?method=artist.getinfo&artist=#{artist}&api_key=f5cb791cfb2ade77749afcc97b5590c8&format=json"
uri = URI(url)
response = Net::HTTP.get(uri)
response = JSON.parse(response)
render json: response
end
and we are good to go to display the json on the view.
If you need the param in the helper, just pass params[:name] to the helper as a parameter.
about(param[:name]) #wherever you are calling this method in the controller or view
def about(artist)
url = "http://ws.audioscrobbler.com/2.0/?method=artist.getinfo&artist=#{artist}&api_key=f5cb791cfb2ade77749afcc97b5590c8&format=json"
uri = URI(url)
response = Net::HTTP.get(uri)
JSON.parse(response)
end

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.

Getting data out of a JSON Response in Rails 3

So I am trying to pull tweets off of Twitter at put them into a rails app (Note because this is an assignment I can't use the Twitter Gem) and I am pretty confused.
I can get the tweets I need in the form of a JSON string but I'm not sure where to go from there. I know that the Twitter API call I'm making returns a JSON array with a bunch of Tweet objects but I don't know how to get at the tweet objects. I tried JSON.parse but was still unable to get the required data out (I'm not sure what that returns). Here's the code I have so far, I've made it pretty clear with comments/strings what I'm trying for. I'm super new to Rails, so this may be way off for what I'm trying to do.
def get_tweets
require 'net/http'
uri = URI("http://search.twitter.com/search.json?q=%23bieber&src=typd")
http = Net::HTTP.new(uri.host, uri.port)
request = Net::HTTP::Get.new(uri.request_uri)
response = http.request(request)
case response
when Net::HTTPSuccess then #to get: text -> "text", date: "created_at", tweeted by: "from_user", profile img url: "profile_img_url"
JSON.parse(response.body)
# Here I need to loop through the JSON array and make n tweet objects with the indicated fields
t = Tweet.new(:name => "JSON array item i with field from_user", :text "JSON array item i with field text", :date => "as before" )
t.save
when Net::HTTPRedirection then
location = response['location']
warn "redirected to #{location}"
fetch(location, limit - 1)
else
response.value
end
end
Thanks!
The JSON.parse method returns a ruby hash or array representing the json object.
In your case, the Json is parsed as a hash, with the "results" key (inside that you have your tweets), and some meta data: "max_id", "since_id", "refresh_url", etc. Refer to twitter documentation for a description on the fields returned.
So again with your example it would be:
parsed_response = JSON.parse(response.body)
parsed_response["results"].each do |tweet|
t = Tweet.new(:name => tweet["from_user_name"], :text => tweet["text"], :date => tweet["created_at"])
t.save
end

Validating URL by making request

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..

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