MtGox price ticker through Ruby - ruby-on-rails

This should be simple, given the public nature of the data, but for some reason my Ruby script is timing out on making the request.
The URL is http://mtgox.com/api/1/BTCGBP/ticker - works fine in browsers, and returns the expected JSON.
require 'net/https'
require 'uri'
uri = URI.parse('https://mtgox.com/api/1/BTCGBP/ticker')
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true if uri.scheme == 'https'
resp, response = http.post(uri.request_uri, nil)
This, however, returns the Timeout::Error: execution expired exception (every time) from the same box. I'm probably missing something really obvious; can anyone help?
Thanks

I tried your code in my environment and everything was ok. Can you write something more about this error, in which line it happened etc. ?
And are you sure to use POST verb (RESTful) ? What do you want to do ? I modified your code:
require 'net/https'
require 'uri'
uri = URI.parse('https://mtgox.com/api/1/BTCGBP/ticker')
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true if uri.scheme == 'https'
resp = http.get(uri.request_uri)
puts resp.body
I use GET verb and I got JSON.

Related

Rails App on Google Cloud: URI must be ascii only

I have a working request on localhost, which basically calls and endpoint using an address
def stuart_validate_address(address)
require 'uri'
require 'net/http'
### not working with accents like Calàbria
# url = URI("https://api.stuart.com/v2/addresses/validate?type=picking&address=#{address}")
# url = URI.parse("https://api.stuart.com/v2/addresses/validate?type=picking&address=#{address}")
url = URI.parse(URI.escape("https://api.stuart.com/v2/addresses/validate?type=picking&address=#{address}"))
http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
request = Net::HTTP::Get.new(url)
request["authorization"] = "Bearer #{AUTH_TOKEN}"
request.body = "{}"
response = http.request(request)
JSON.parse(response.read_body)
end
If I use the endpoint with Postman it works, if I do the call with localhost it works. But once we are on production (gcloud) it complains about
URI::InvalidURIError
URI must be ascii only "https://api.stuart.com/v2/addresses/validate?type=picking&address=Córsega 494, 08025, Barcelona"
I know I have to parse it and escape it, but I can't figure out why I still have the same error. Also I am curious why it's working on localhost and postman, and not in Rails production environment.
The issue is that you have an acute ó in your url.
If you are using Rails, you can use string#parameterize
Or if plain Ruby, you use i18n gem:
require "i18n"
I18n.transliterate("Olá Mundo!")
=> "Ola Mundo!"

Rails http GET request with no ssl verification and basic auth

I am trying to make a http get request as specified in the title.
What I've written:
uri = URI.parse("https://myaddress.com")
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
#data = http.get(uri.request_uri)
The request is sent where I want it to be sent and I receive an Unauthorized response (as expected, because I did not specify the basic auth).
I've tried
http.basic_auth 'user', 'pass'
But there's no such method for the type of my http variable.
How can I add the auth details?
Update: I tried to use something like here RUBY - SSL, Basic Auth, and POST, but after replacing Post with Get, I cannot use the 'use_ssl', nor 'verify_mode' attributes (I get no such attribute error).
Update 2: I figured out that I can set the 'use_ssl' attribute on a Net::HTTP object and the 'basic_auth' on a Net::HTTP::Get object.
Now the question is how can I make them work together?
Well, I ended up finding an answer. Maybe this will help others:
url = URI.parse('https://myaddress.com')
req = Net::HTTP::Get.new(url.path)
req.basic_auth 'user', 'pass'
sock = Net::HTTP.new(url.host, url.port)
sock.use_ssl = true
sock.verify_mode = OpenSSL::SSL::VERIFY_NONE
resp = sock.start {|http| http.request(req) }

How to solve error with using NET::HTTP

I want to post some data using standard ruby class NET::HTTP.
I have controller from examples
def request
require "net/http"
require "uri"
uri = URI.parse("http://google.com/")
# Shortcut
response = Net::HTTP.get_response(uri)
# Will print response.body
Net::HTTP.get_print(uri)
# Full
http = Net::HTTP.new(uri.host, uri.port)
response = http.request(Net::HTTP::Get.new(uri.request_uri))
end
My application gives error -
undefined method `content_mime_type' for #<Net::HTTPMovedPermanently 301 Moved Permanently readbody=true>
Why this is happening ?
Problem might be that in the last line of your code, there are two requests happening. The code translates to:
response = http.request(<result>) where the <some result> part is the return value from the call Net::HTTP::Get.new(uri.request_uri)
I think you were trying to do this instead:
http.request(uri.request_uri)

How do I touch a URL with rails?

I have a json URL supplied by sendgrid. All it needs to be is touched. How would I do this?
def suspend
#user = User.find(params[:id])
#user.update_attribute("suspended", true)
# the url I need to touch => https://sendgrid.com/api/unsubscribes.add.xml?api_user=username%40website.com&api_key=secret_password&email=#{#user.email}
end
You can use Net::HTTP.get from standard library (see docs):
require 'net/http'
Net::HTTP.get URI("https://sendgrid.com/api/unsubscribes.add.xml?api_user=username%40website.com&api_key=secret_password&email=#{#user.email}")
Updated:
For HTTPS you can do smth like that:
require "net/https"
uri = URI.parse("https://www.google.com")
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
request = Net::HTTP::Get.new(uri.request_uri)
# request = Net::HTTP::Head.new(uri.request_uri) - get response without body
response = http.request(request)
Nice article on the subject - Ruby Net::HTTP Cheat Sheet.
Install httpclient gem
HTTPClient.get("https://sendgrid.com/api/unsubscribes.add.xml?api_user=username%40website.com&api_key=secret_password&email=#{#user.email}")
maybe try ActionDispatch GET http://api.rubyonrails.org/classes/ActionDispatch/Request.html#method-i-GET
require 'open-uri'
open("http://pragprog.com/") { |f| f.gets }
result? just one row, not the whole page:
"<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1//EN\"\n"

Net::HTTP::Put.new(url.path) shows the 401 error in RUby

HI ,
i am new to ROR
i am writing Ruby code for calling API blogs
i have written ruby code for
Creating the blog by
require 'net/http'
require 'uri'
url = URI.parse('http://localhost:3000/api/blogs/create.xml')
req = Net::HTTP::Post.new(url.path)
req.basic_auth 'a', 'a'
req.set_form_data({'blogpost[title]'=>'TestingAPIBlogposttitle',
'blogpost[description]'=>'Testing api desc',
'blogpost[category_id]'=>'3121'}, ';')
res = Net::HTTP.new(url.host, url.port).start {|http| http.request(req)}
case res
when Net::HTTPSuccess, Net::HTTPRedirection
puts res.body
else
res.error!
end
which runs successfully by creating a new blog
And i have a search code
require 'net/http'
require 'uri'
require 'cgi'
## Change this part according to the api to be accessed and the params to be passed.
uri = URI.parse( "http://localhost:3000/api/blogs/show/blogtitle.xml" )
http = Net::HTTP.new(uri.host, uri.port)
request = Net::HTTP::Get.new(uri.path)
request.basic_auth 'a', 'a'
response = http.request(request)
puts response.body
which returns the
<?xml version="1.0" encoding="UTF-8"?>
<blogpost>
<created-at type="datetime">2010-09-02T08:18:22Z</created-at>
<description><p>Blog desc</p></description>
<slug>blogtitle</slug>
<title>blogtitle</title>
<user>
<firstname>admin</firstname>
<lastname>k</lastname>
<login>admin</login>
</user>
</blogpost>
Now i am trying to Update a BLog
for this how to write the code
i tried by simply changing the POST.new by PUT.new
but it didnt works for me
its showing me the error even if i gave admin User credentials
It might be worth trying a POST request but also adding a _method = 'put' parameter to the request. Rails can simulate a PUT request in this way though I would expect it to respond correctly to an HTTP PUT too.

Resources