简体   繁体   English

Ruby on Rails HTTP请求问题

[英]Ruby on rails HTTP request issue

I am an newbie to Ruby on Rails. 我是Ruby on Rails的新手。 I have a url which points to a JSON output. 我有一个指向JSON输出的网址。 When I ran the URL directly like http://user:pass@myurl.com/json , I am getting the response without any authendication. 当我像http:// user:pass@myurl.com/json这样直接运行URL时,得到的响应没有经过任何身份验证。 However http://myurl.com/json requires a username and password through a standard apache pop up authentication box. 但是http://myurl.com/json需要通过标准的Apache弹出身份验证框输入用户名和密码。 I have tried to access this URL from my rails controller like the following: 我试图从我的rails控制器访问此URL,如下所示:

result = JSON.parse(open("http://user:pass@myurl.com/json").read)

When I try to do, I just get an error which says ArgumentError, userinfo not supported. 当我尝试执行此操作时,我仅收到一条错误消息,指出ArgumentError,不支持userinfo。 [RFC3986] [RFC3986]

Also I have tried the below one. 我也尝试了以下之一。 I am getting a 401-Unauthorized error 我收到401-未经授权的错误

open("http://...", :http_basic_authentication=>[user, password])

How can I make a request that works in this case. 在这种情况下,我该如何提出要求。 Any help would be appreciated. 任何帮助,将不胜感激。

You need to use Net::HTTP (or some other HTTP client ). 您需要使用Net :: HTTP (或其他HTTP客户端 )。

require 'net/http'
require 'uri'
require 'json'

uri = URI('http://myurl.com/json')
req = Net::HTTP::Get.new( uri )
req.basic_auth 'user', 'pass'
res = Net::HTTP.start(uri.hostname, uri.port) {|http|
  http.request(req)
}
result = JSON.parse(res.body)
puts result

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM