RUBY - SSL, Basic Auth, and POST - ruby

I'm having quite a hard time with this -- seems like there are a few snippets of code lying around that I can't seem to piece together. I'm simply trying to POST key/value pairs, but getting Connection refused - connect(2) (Errno::ECONNREFUSED). Help!
require 'net/http'
require 'net/https'
require 'uri'
#http = Net::HTTP.new('https://my.url.com/path', 443)
#http.use_ssl = true
#http.start() { |http|
req = Net::HTTP.post_form(
URI.parse('https:///my.url.com/path'),
{'key1' => 'value1', 'key2' => 'value2'}
)
req.basic_auth 'username', 'password'
response = http.request(req)
puts response.body
}

HTTP#post_form will execute directly, ignoring your other settings. Try this instead:
require 'net/http'
require 'uri'
url = URI.parse('https://my.url.com/path')
req = Net::HTTP::Post.new(url.path)
req.basic_auth 'user', 'pass'
req.use_ssl = true
req.form_data({'key1' => 'val1', 'key2' => 'val2'})
resp = Net::HTTP.new(url.host, url.port).start {|http| http.request(req) }
puts resp
You are likely to run into trouble with the server's certificates. See my other post for instructions on how to get/configure them.

Found this question during my search for a solultion, and just to be clear emboss' code as is is non functional. What I got working is this (inside of a larger Sinatra application):
require 'net/http'
require 'net/https'
require 'uri'
set :api_username, 'usr'
set :api_passwor, 'pswd'
def do_auth_check params
puts params.inspect
url = URI.parse("https://my_auth_site.com:443/authenticate")
req = Net::HTTP::Post.new(url.path)
req.basic_auth options.api_username, options.api_password
req.set_form_data({'username' => params[:name], 'password' => params[:pass]})
sock = Net::HTTP.new(url.host, url.port)
sock.use_ssl = true
res = sock.start {|http| http.request(req) }
# you're on your own down here to identify success/failure, but for me 2xx/3xx was ok and 401/404/500/etc would be failure
return true if res.code.to_i < 400
return "Error logging in"
end

Related

team city api returns json example

I'm struggling with getting results from the team city api in JSON
require 'open-uri'
url = ".../app/rest/buildQueue/"
c = Curl::Easy.new(url) do |curl|
curl.headers["Content-type"] = "application/json"
curl.http_auth_types = :basic
curl.username = 'user'
curl.password = 'password'
end
c.perform
puts c.body_str
I get a bunch of xml text
You need to use the Accept header to control the response type:
e.g (command line)
curl --url http://xxx/app/rest/buildQueue/ -H Accept:"application/json"
Documentation Reference
also you can use "net/http"
require 'net/http'
require 'uri'
url = URI('http://localhost:8111/httpAuth/app/rest/agents')
req = Net::HTTP::Get.new(url)
req['Accept'] = 'application/json'
req.basic_auth 'admin', 'admin'
res = Net::HTTP.start(url.hostname, url.port) {|http|
http.request(req)
}
puts res.body

uninitialized constant Net::HTTP::Patch (NameError)

I keep the error "/usr/local/bin/git_flow_tools.rb:55:in `set_issue': uninitialized constant Net::HTTP::Patch (NameError)"
I'm require this:
require 'rubygems'
require 'net/http'
require 'net/https'
require 'uri'
require 'timeout'
require 'json'
require 'pp'
This function fail:
def self.set_issue(user, repo, number, data)
uri = URI.parse('https://api.github.com')
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true if uri.scheme == 'https'
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
path = URI.escape("/repos/#{user}/#{repo}/issues/#{number}")
req = Net::HTTP::Patch.new(path)
req['Content-Type'] = 'application/json'
req['Accept'] = 'application/json'
req['Authorization'] = 'token OAUTH-TOKEN'
req.body = data
begin
Timeout::timeout(30) { JSON.parse http.request(req).body }
rescue Exception => e
puts "Failed to contact github #{e}"
end
end
Other methods like Get, Put or Post works fine.
Any ideas?
try to add after requirements
class Net::HTTP::Patch < Net::HTTPRequest
METHOD = 'PATCH'
REQUEST_HAS_BODY = true
RESPONSE_HAS_BODY = true
end

New York Public Library search query

I am attempting to access the NY Public Library digital collection through their api.
The ruby code I am using to make the call is:
require 'sinatra'
require 'pp'
require 'httparty'
get '/' do
url = "http://api.repo.nypl.org/api/v1/items/8568ccd0-c614-012f-1d74-58d385a7bc34.json"
uri = URI.parse(url)
http = Net::HTTP.new(uri.host, uri.port)
headers = { "Authorization" => "Token token=mytoken" }
request = Net::HTTP::Get.new(uri.request_uri, headers)
response = http.request(request)
puts response
#response = response.body
erb :index
end
So, a couple of questions:
This produces no result, nothing comes back with the puts response in the terminal, not even an error message. What am I doing wrong?
In any case, how do I attach a query at the end of the uri string? BY adding a ? followed by the query? So, for example, ?leonardodavinci
Recommend you play around at the irb command prompt, e.g.
irb [enter]
Looks like not authorized perhaps? I eventually get => nil myself with:
irb(main):003:0> require 'sinatra'
=> true
irb(main):004:0> require 'pp'
=> true
irb(main):005:0> require 'httparty'
=> false
irb(main):006:0> url = "http://api.repo.nypl.org/api/v1/items/8568ccd0-c614-012f-1d74-58d385a7bc34.json"
=> "http://api.repo.nypl.org/api/v1/items/8568ccd0-c614-012f-1d74-58d385a7bc34.json"
irb(main):007:0> uri = URI.parse(url)
=> #<URI::HTTP:0x9826744 URL:http://api.repo.nypl.org/api/v1/items/8568ccd0-c614-012f-1d74-58d385a7bc34.json>
irb(main):008:0> http = Net::HTTP.new(uri.host, uri.port)
=> #<Net::HTTP api.repo.nypl.org:80 open=false>
irb(main):009:0> headers = { "Authorization" => "Token token=mytoken" }
=> {"Authorization"=>"Token token=mytoken"}
irb(main):010:0> request = Net::HTTP::Get.new(uri.request_uri, headers)
=> #<Net::HTTP::Get GET>
irb(main):011:0> response = http.request(request)
=> #<Net::HTTPUnauthorized 401 Authorization Required readbody=true>
irb(main):012:0> puts response
#<Net::HTTPUnauthorized:0x9938a74>
=> nil
irb(main):013:0>

Creating Gist from a Ruby script

Is there a way to create an Anonymous (public or private) gist using net/http or net/https?
This worked for me.
require 'net/http'
require 'json'
uri = URI("https://api.github.com/gists")
payload = {
'description' => "My test gist",
'public' => true,
'files' => {
'test.txt' => {
'content' => "This is a test!\n\nI am making a public gist."
}
}
}
req = Net::HTTP::Post.new(uri.path)
req.body = payload.to_json
puts req.inspect
puts req.body.inspect
# GitHub API is strictly via HTTPS, so SSL is mandatory
res = Net::HTTP.start(uri.hostname, uri.port, :use_ssl => true) do |http|
http.request(req)
end
puts res.inspect
puts res.body.inspect
Result: My test gist
This gem will do the trick for you https://github.com/defunkt/gist!
For the record, it does require net/https.

How to post json data with Rest API

require 'net/http'
require 'uri'
postData = Net::HTTP.post_form(URI.parse('http://localhost/restapi/index.php/api/posts'),
{'id'=>9,'firstname'=>"test","lastname"=>"test"})
puts postData.body
How can I send data in JSON form?
#toSend = {"id" =>5,"firstname" => "anurag","lastname" => "arya"}
I also tried this but it did not work:
#toSend.to_json
Example:
require 'rubygems'
require 'net/http'
require 'uri'
require 'json'
url = "http://localhost/restapi/index.php/api/posts"
uri = URI.parse(url)
data = {"id"=>11,
"firstname"=>"PWD","lastname"=>"last"}
headers = {'Content-Type' =>'application/json',
'Accept-Encoding'=> "gzip,deflate",
'Accept' => "application/json"}
http = Net::HTTP.new(uri.host,uri.port) # Creates a http object
#http.use_ssl = true # When using https
#http.verify_mode = OpenSSL::SSL::VERIFY_NONE
response = http.post(uri.path,data.to_json,headers)
puts response.code
puts response.body
postData=Net::HTTP.post_form(URI.parse('http://localhost/oecprashant/yiiIndex.php/api/rubyREST'),
{'data'=>jsonData})

Resources