2011-08-30 82 views
0

我试图验证登录过程中,在我登录过程中如果用户名&密码正确,那么用户将登录到他的仪表板,但如果用户名为&,密码为错了,我得到一个XML响应。在rails中使用Nokogiri捕获XML响应3.0.9

以下是session_controller代码

{

require 'net/http' 
require 'uri' 
require 'open-uri' 
require 'nokogiri' 
class SessionsController < ApplicationController 
def new 
@title = "Sign in" 

end 

def create 

    redirect_to "http://<SERVER_IP>/billing/api/login?u=#{params[:session][:email]}&p=#{params[:session][:password]}" 

a = "http://<SERVER_IP>/billing/api/login?u=#{params[:session][:email]}&p=#{params[:session][:password]}" 

doc = Nokogiri::XML(open(a).read) 
    doc.css('status').each do |link| 


    # Create error message and re-render signin page 

@b = link.content 


end 
end 

def destroy 
    sign_out 
    redirect_to root_path 
end 
end 

}

我得到这样的XML响应从服务器

<?xml version="1.0" encoding="UTF-8" standalone="yes"?> 
<action> 
<name>login</name> 
<status>failed</status> 
<status_message>Error description</status_message> 
</action> 

那些我得到这个反应我想使用上面的XML响应来刷新错误消息。

如果任何人有任何想法会拯救我的一天。

回答

0

嘿人我终于上述functionality.That做是不是因为我想给其他用户,我在这里粘贴确切的片断大量艰巨

def create 

a = "http://<SERVER IP>/billing/api/login?u=#{params[:session][:email]}&p=#{params[:session][:password]}" 

# Nokogiri Gem is used to Catch the XML response from the MOR & call the appropriate action on the received status 

    doc = Nokogiri::XML(open(a)) 
    doc.xpath('/action/status').each do |link| 
    @abc = link.content 
    end 

    # Condition to check whether the received response is 'Ok' or 'Failed' 

    if @abc == 'failed' 

      flash[:notice] = "Invalid Username/Password" # If condition is failed redirect to root page 
      redirect_to '/' 
      else 
       # if condition is 'ok' redirect to MOR user dashboard 

       redirect_to "http://<SERVER IP>/billing/api/login?u=#{params[:session][:email]}&p=#{params[:session][:password]}" 
     end           

0

引入nokogiri为您提供了直接访问到文档的文本:

require 'nokogiri' 

doc = Nokogiri::XML(
'<?xml version="1.0" encoding="UTF-8" standalone="yes"?> 
<action> 
<name>login</name> 
<status>failed</status> 
<status_message>Error description</status_message> 
</action>' 
) 

irb你会看到:

doc.text 

>> "\nlogin\nfailed\nError description\n" 

您可以简化您的代码是这样的:

doc = Nokogiri::XML(open(a)) 

if doc.text['failed'] 
    ...