如何在Perl中访问简单的SOAP服务

时间:2011-09-20 16:49:21

标签: perl soap

我目前正在使用SOAP :: Lite来处理perl和SOAP。

我有一个简单的SOAP服务器似乎运行良好:

#!perl -w

  use SOAP::Transport::HTTP;

  use Demo;

  # don't want to die on 'Broken pipe' or Ctrl-C
  $SIG{PIPE} = $SIG{INT} = 'IGNORE';

  my $daemon = SOAP::Transport::HTTP::Daemon
    -> new (LocalPort => 801)
    -> dispatch_to('/home/soaplite/modules')
  ;

  print "Contact to SOAP server at ", $daemon->url, "\n";
  $daemon->handle;

它包含一个名为Demo的小类,它只检索系统总内存:

Demo.py

#!/usr/bin/perl
use Sys::MemInfo qw(totalmem freemem totalswap);

print "total memory: ".(&totalmem / 1024)."\n";

我有一个下面用PERL编写的SOAP客户端示例,虽然我不确定如何与服务器通信(因为我在这里跟随的tutorial是相切的,例如检索Demo的结果来自客户端的.py类:

  #!perl -w

  use SOAP::Lite;

  # Frontier http://www.userland.com/

  $s = SOAP::Lite 
    -> uri('/examples')
    -> on_action(sub { sprintf '"%s"', shift })
    -> proxy('http://superhonker.userland.com/')
  ;

  print $s->getStateName(SOAP::Data->name(statenum => 25))->result; 

任何帮助都将非常感谢:)

2 个答案:

答案 0 :(得分:4)

对于服务器脚本,dispatch_to方法获取要加载的包的路径以及包本身的名称。如果传递第三个参数,它将限制服务器可见的方法的名称。 (例如,名为memorytime的2个方法,将Demo::time作为第3个参数传递将使memory对客户端服务不可见。)

文件server.pl

my $daemon = SOAP::Transport::HTTP::Daemon
    -> new (LocalPort => 801)
    -> dispatch_to('/home/soaplite/modules', 'Demo')
;

您的Demo包应该是包含返回值的方法的包。我无法在我的系统上编译Sys :: MemInfo,所以我只使用了localtime。我不确定你为什么要为你的软件包Demo.py命名,但是Perl软件包必须有扩展名pm,否则它们将无法正确加载。

File Demo.pm

#!/usr/bin/perl

package Demo;

#use Sys::MemInfo qw(totalmem freemem totalswap);

sub memory {
    #print "total memory: ".(&totalmem / 1024)."\n";
    return "Can't load Sys::MemInfo, sorry";
}

sub time {
    my $time = localtime;
    return $time;
}

1;

对于客户端代码,必须正确指定2个重要部分,proxyuri。代理是soap Web服务的url路径。由于您将服务器脚本作为守护程序进程运行,因此您的路径只是网站的URL。我的电脑没有网址,因此我使用了http://localhost:801/。 801是您在上面指定的端口。如果您在不同的Web服务器(例如Apache)中作为cgi脚本运行,那么您需要指定要调用的cgi脚本(例如http://localhost/cgi-bin/server.pl,将server.pl中的包更改为{{1 }}

SOAP::Transport::HTTP::CGI可能是最令人困惑的,但它是Web服务返回的xml文件的命名空间。打开uri以查看Web服务返回的xml文件。 uri应该只是服务器的名称。即使你切换端口或cgi调度方法,这个uri保持不变。

文件test.pl

+trace => 'debug'

答案 1 :(得分:3)

我将回收这两个答案以获取提示: