The following (and other similar) HTTP request to the Google geocoding API comes out correctly when I paste it into my browser
http://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&sensor=false
And when I do the following in Ruby
url = URI.parse('http://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&sensor=false')
req = Net::HTTP::Get.new(url.path)
res = Net::HTTP.start(url.host, url.port) {|http|
http.request(req)
}
puts res.body
I get
{
"results" : [],
"status" : "REQUEST_DENIED"
}
This is the same error I get when not setting the "sensor" property for example, but that's not the problem.
Any suggestions?
You need to use #request_uri instead of #path, or your query parameters will not be included:
url = URI.parse('http://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&sensor=false')
url.path
# => "/maps/api/geocode/json"
url.request_uri
# => "/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&sensor=false"
Related
I created a method to change a subscription on an online platform through the API made available. The request returns status 200, but the change does not appear on the platform.
The method is as follows:
def self.update_subscription_item_value(subscription_id, item_id, value)
url = URI("https://api.iugu.com/v1/subscriptions/#{subscription_id}")
http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true
request = Net::HTTP::Put.new(url)
request['authorization'] = 'Basic ' + Base64.encode64(Iugu.api_key + ':').chomp
request.body = "{\"subitems\":[{\"id\":\"#{item_id}\",\"quantity\":\"#{value}\"}]}"
response = http.request(request)
puts response.read_body
end
request return: Net::HTTPOK 200 OK readbody=true
does anyone know why I didn't get any changes to the platform?
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"}
I have a ROR application which wants to GET the contents from a URI through the REST mechanism. Although the URI is able to get the response back when the URI is used in the browser or through the curl. But when sent through the ROR application, it gives the following response: { "error": "\n\n\n \n\n\n Sinatra doesn’t know this ditty. \n \n \n Try this:\n get '/works' do\n \"Hello World\"\nend \n \n\n\n", "status": 404 }. Can someone please help what might be the possible reason for getting such issues with the GET request.
def get_result(url, options = { content_type: 'json' })
uri = URI.parse(url) options[:headers] ||= {}
options[:headers]['Host'] = uri.host
conn = faraday_conn(options[:content_type], options)
.....
if options[:data]
response = conn.post url, {}, options[:headers] do |request|
request.body = options[:data]
end
else response = conn.get url, {}, options[:headers]
end
i am trying to call my Rails app using Ruby code .
I m having 2 tables .
Blogposts (id,name,slug,desc)
Comments (id,data,node_id,node_type)
I m trying to post a comment through my ruby code.
The Url for me is like
http://localhost:3000/api/blogs/comment.xml?slug=blogtitle-0&comment=aaaaaaaaaaaaaaa
I dont know how to write Ruby post code for this.
The one is tried is
require 'net/http'
require 'uri'
url = URI.parse('http://localhost:3000/api/blogs/comment.xml?slug=blogtitle-0')
req = Net::HTTP::Post.new(url.path)
req.basic_auth 'aruna', 'aruna'
req.set_form_data({'comment[data]'=>'aaaaaaaaaaaaaaa'}, ';')
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
end
Please help in fixing this
Edit: The same thing i am trying using Java using Jersey library file .
Here also i am not getting the result.
The one i tried in Java is,
blogBean = objBlogWrapper.postComment(slug,comment);
public BlogBean postComment(String slug, String comment) {
System.out.println(slug+""+comment);
// Create a multivalued map to store the parameters to be send in the REST call
MultivaluedMap<String, String> newBlogParam = new MultivaluedMapImpl();
// newBlogParam.add("blogpost[slug]", slug);
// newBlogParam.add("comment[data]", comment);
newBlogParam.add("slug", slug);
newBlogParam.add("comment", comment);
BlogBean blogBean = null;
try {
blogBean = webResource.path(ConfigurationUtil.POST_COMMENT).header(ConfigurationUtil.AUTHENTICATION_HEADER, authentication)
.type(MediaType.APPLICATION_FORM_URLENCODED_TYPE).accept(MediaType.APPLICATION_XML_TYPE).post(BlogBean.class, newBlogParam);
}catch (UniformInterfaceException uie) {
if (uie.getResponse().getStatus() == 401) {
System.out.println("Can not authenticate user "+ConfigurationUtil.userName +
". Please check your username/password and try again." );
} else {
System.out.println("Error when trying to talk to app. " +
"HTTP status code "+uie.getResponse().getStatus()+"returned. Finishing.");
}
return null;
} catch (ClientHandlerException che) {
System.out.println("Error when trying to talk toapp. Network issues? " +
"Please check the following message and try again later: "+che.getMessage());
return null;
}
return blogBean;
}
where my ConfigurationUtil.POST_COMMENT="api/blogs/comment.xml";
The above doesnt show me any error nor the comment is posted ..
Please give suggestions.
Here you go,
host, phost = ['http://localhost:3000', 'http://proxyhost:2521' ]
user, password = [ 'user_name' , 'password' ]
url, p_url = [URI.parse(host), URI.parse(phost)]
resp = nil
http = Net::HTTP.new(url.host, url.port, p_url.host, p_url.port)
req = Net::HTTP::Post.new(url.path)
req.basic_auth user, password
req.set_content_type 'application/xml'
req.body = 'your_request_body'
resp = http.start{|h| h.request(req)}
You may not need a proxy host at all. But just in case if you want your request proxied through, you can use that. The resp object will have your response.
With Faraday you just do
body_resp = Faraday.post 'http://localhost:3000/api/blogs/comment.xml', {:slug => 'blogtitle-0', :comment => 'aaaaaaaaaaaaaaa'}.body
Using some external gem can help because Net::Http class in Ruby is not the most simplest API.
I am trying to implement call this API method in Ruby https://zferral.com/api-docs/affiliate#aff-create-usage-example which expects this object:
{ "affiliate" : {
"email" : "john#example.com",
"send_user_email" : "1" }}
Using a Httparty class, I call this:
result = self.class.post("/api/#{#apikey}/affiliate/create.xml", :body => {:affiliate => {:email => email}})
Unfortunately, the API keeps sending me "Email is required". I have tried to switch to json, I am changed :body with :query, etc...
Anybody could show me how to call the affiliate/create method correctly?
Thank you.
You're sending json, but posting it to create.xml --- in rails, this will auto-set the content type to be xml when you post to create.xml
Try posting to /api/#{#apikey}/affiliate/create.json
If that doesn't work --- are you following the class design that HTTParty really likes? http://railstips.org/blog/archives/2008/07/29/it-s-an-httparty-and-everyone-is-invited/
This is how I fixed my issue:
url = URI.parse('https://xxxx.zferral.com/api/xxx/affiliate/create.xml')
http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
request = Net::HTTP::Post.new(url.path)
request.body = "<?xml version='1.0' encoding='UTF-8'?><affiliate><email>#{email}</email><send_user_email>0</send_user_email></affiliate>"
request.content_type = 'text/xml'
response = http.request(request)