用Perl调用SOAP服务
用Perl写了一段调用SOAP服务的代码。本来很简单的一个事情,研究了大概两天,主要还是对Perl不太熟。
调用的这个SOAP服务比较奇怪,没有WSDL文件,也没有说明文档,我只是根据之前开发人员用Java写的一个例子改写的。 这里面有两个地方相对特殊,一是需要验证,二是直接将Soap消息(SOAP Envelop)发送给服务器端处理,具体代码如下:
1 use XML::Simple;
2 use IO::File;
3 use LWP::UserAgent;
4 use HTTP::Request;
5 use HTTP::Headers;
6
7 open REQ, '<Req.xml';
8 my $input = "";
9
10 while (<REQ>)
11 {
12 chomp;
13 $input = $input.$_."\n";
14 }
15
16 #Generate HTTP Header
17 my $h = HTTP::Headers->new();
18 $h->authorization_basic( $username, $passwd );
19 $h->header( SOAPAction => 'http://tempuri.org/Register' );
20 $h->content_type('text/xml;charset=utf-8');
21
22 #Generate Request, including method, address, header and so on
23 my $request = HTTP::Request->new( POST,
24 'http://services_address', $h );
25 $request->protocol('HTTP/1.0');
26 $request->content($input);
27
28 #Post the request
29 my $userAgent = LWP::UserAgent->new();
30 my $response = $userAgent->request($request);
31
32 #print the result
33 my %keys = %{$response};
34 foreach $key ( keys %keys ) {
35 print $key, "=>", $keys{$key}, "\n";
36 }
2 use IO::File;
3 use LWP::UserAgent;
4 use HTTP::Request;
5 use HTTP::Headers;
6
7 open REQ, '<Req.xml';
8 my $input = "";
9
10 while (<REQ>)
11 {
12 chomp;
13 $input = $input.$_."\n";
14 }
15
16 #Generate HTTP Header
17 my $h = HTTP::Headers->new();
18 $h->authorization_basic( $username, $passwd );
19 $h->header( SOAPAction => 'http://tempuri.org/Register' );
20 $h->content_type('text/xml;charset=utf-8');
21
22 #Generate Request, including method, address, header and so on
23 my $request = HTTP::Request->new( POST,
24 'http://services_address', $h );
25 $request->protocol('HTTP/1.0');
26 $request->content($input);
27
28 #Post the request
29 my $userAgent = LWP::UserAgent->new();
30 my $response = $userAgent->request($request);
31
32 #print the result
33 my %keys = %{$response};
34 foreach $key ( keys %keys ) {
35 print $key, "=>", $keys{$key}, "\n";
36 }