Perl wsdl webservice call - perl

I am new to perl webservice call.
I am calling a wsdl webservice function and I am getting the response as 400 bad request error. I tried and googled many sites but could not get successful. Please help me in solving this issue. Below is my code.
use SOAP::Lite;
my $lite = SOAP::Lite -> service('http://localhost:8080/service.svc?wsdl');
my $arg1 ="SRC";
my $arg2 = "ARG";
my #arg3 = ('test1','test2','test3');
my #res = $lite->Func($arg1,$arg2,#arg3);
print "#res";

I just had similar problem and seemed that SOAP::Lite may have a bug concerning handling complex data structures.
Whatever, if your SOAP method (Func) needs 3 arguments, the last one should be reference to array.
Also, with use SOAP::Lite qw(trace) you could debug request envelope.

If you are not restrict at SOAP::Lite, I will request you to please have a look at XML::Compile::SOAP::Client

I'm not sure how much of a difference there is between a WSDL and an ASMX web service. If not much, try this code sample which works for me.
my $soap = SOAP::Lite
-> uri('http://foo.com')
-> on_action( sub { join '/', 'http://foo.com', $_[1] } )
-> proxy('http://foo/services/GetEmailAddress/Service.asmx');
my $method = SOAP::Data->name('GetEmailAddress')
->attr({xmlns => 'http://foo.com/'});
my #params = ( SOAP::Data->name(username => $user) );
my $email = $soap->call($method => #params)->result;
Input is a username, output is an email address. The ASMX web service was created in .NET 3, I believe.
Everything I know about how this works I learned from http://msdn.microsoft.com/en-us/library/ms995764.aspx.

Related

Using variable for HTTP request headers with Perl

I am trying to write a function to create HTTP requests (POST and GET mostly) in Perl. I am keeping everything generic by using variables so that I don't have to worry about the type of request, the payload, headers, etc, however HTTP::Request->header() doesn't seem to like my variable:
my($req_type, $headers, $endpoint, $args, $request, $jsonfile) = #_;
my $ua = LWP::UserAgent->new;
my $req = HTTP::Request->new($req_type => $endpoint);
$req->content_type('application/json');
foreach (#$headers) {
$req->push_header($_);
}
$req->content($args);
$req->content($request);
print "request : ".$req->as_string;
I tried a few different approches, and using push_header got me the closest, but I realize it may not be the best solution. I think it might have something to do with single quotes getting passed in:
#headers = "'x-auth-token' => '$_token'";
I can post more of the code if it is helpful. I'm hoping some Perl guru will know exactly what I'm doing wrong. I'm sure it's something to do with the format of the string I'm passing in.
#headers = "'x-auth-token' => '$_token'";
The header function expects to be passed two arguments. The header name and the header value.
You are passing it one argument: a string containing a fragment of Perl code.
You need to format your data more sensibly.
my %headers = (
"x-auth-token" => $_token;
);
and
foreach my $header_name (keys %headers) {
$req->push_header($header_name => $headers{$header_name});
}

Extract specific XML element in CDATA taken from SOAP::Lite Response Hash

My code below is connecting to a .asmx web service to get data.
The code extractes the CDATA into %keyHash below.
Rather than parsing the entire CDATA, is it possible to grab a specific data element in the SOAP CDATA by calling out it's path?
I read that I could use $soap->valueof() to get the data, is that correct? and that this would require use of XPATH?
I ask as I am unfamiliar with this and I do not know if I am on the right path, are there other ways to do this?
My $soap->valueof('//Images/Front') attempts have failed, saying that, my first time using XPATH, could be getting it wrong but at this point I am guessing if this is the right way to go.
Any direction on whether I am on the right or wrong path in using valueof() would be appreciated!
Here is the code, it works. I have also included the obscurated CDATA data extracted from %keyHash.
use SOAP::Lite +trace => 'all';
$soap = SOAP::Lite
-> uri('..../')
-> on_action( sub { join '/', '.....', $_[1] } )
-> proxy('......asmx');
$method = SOAP::Data->name('methodName')
->attr({xmlns => ...../'});
#params = (
SOAP::Data->name(tran=> 765) ->type(''),
SOAP::Data->name(token => 0)->type(''),
SOAP::Data->name(type=> 1)->type('')
);
%keyHash = %{ $soap->call($method => #params)->body->{'GetmethodNameResponse'}->{'GetmethodNameResult'} };
# iterate through all fields and print them
foreach my $k (keys %keyHash) {
print "$k=$keyHash{$k}\n";
}
Example of the data output, I want the data in the string "THIS_IS_THE_DATA_I_WANT" (unable to put the path here for some reason)
RequestResult=0
Xml=<?xml version="1.0" encoding="utf-8"?>
<Images>
<Front>THIS_IS_THE_DATA_I_WANT</Front>
</Images>
Thank You,
A
I solved this by using the following, hope it helps someone...
use XML::Simple;
%keyhash = %{ $soap->call($method => #params)->body->{'GetCheckXmlResponse'}->{'GetCheckXmlResult'}};
$getxml= %keyhash->{Xml};
$parsexml = XMLin($getxml);
print Dumper($parsexml); # Use this to point to your data and then grab it as per the line below
$frontside = $parsexml->{Images}->{Front};

Perl -- 'Not a HASH reference' error when using JSON::RPC::Client

I'm a newbie in Perl.
I have a JSON-RPC server running at http://localhost:19000 and I need to call checkEmail() method.
use JSON::RPC::Client;
my $client = new JSON::RPC::Client;
my $url = 'http://localhost:19000';
my $callobj = {
method => 'checkEmail',
params => [ 'rprikhodchenko#gmail.com' ],
};
my $res = $client->call($url, $callobj);
if($res) {
if ($res->is_error) {
print "Error : ", $res->error_message;
}
else {
print $res->result;
}
}
else {
print $client->status_line;
}
When I try to launch it it tells following:
perl ./check_ac.pl
Not a HASH reference at /usr/local/share/perl/5.10.1/JSON/RPC/Client.pm line 193.
UPD:
Full stack-trace:
perl -MCarp::Always ./check_ac.pl
Not a HASH reference at /usr/local/share/perl/5.10.1/JSON/RPC/Client.pm line 193
JSON::RPC::ReturnObject::new('JSON::RPC::ReturnObject', 'HTTP::Response=HASH(0x9938d48)', 'JSON=SCALAR(0x96f1518)') called at /usr/local/share/perl/5.10.1/JSON/RPC/Client.pm line 118
JSON::RPC::Client::call('JSON::RPC::Client=HASH(0x944a818)', 'http://localhost:19000', 'HASH(0x96f1578)') called at ./check_ac.pl line 11
This error means that your JSON-RPC server is not actually one, inasmuch as it does not satisfy requirement 7.3. The error is triggered when JSON::RPC::Client assumes the document returned by the JSON-RPC service is well-formed (i.e., a JSON Object), and this assumptions turns out to have been in error. A bug report to the author of JSON::RPC::Client would be an appropriate way to request better error messaging.
I would attack this sort of problem by finding out what the server was returning that was causing JSON::RPC::Client to choke. Unfortunately, JRC fails to provide adequate hookpoints for finding this out, so you'll have to be a little bit tricky.
I don't like editing external libraries, so I recommend an extend-and-override approach to instrumenting traffic with the JSON-RPC server. Something like this (in check_ac.pl):
use Data::Dumper qw();
package JSON::RPC::InstrumentedClient;
use base 'JSON::RPC::Client';
# This would be better done with Module::Install, but I'm limiting dependencies today.
sub _get {
my ($self, #args) = #_;
return $self->_dump_response($self->SUPER::_get(#args));
}
sub _post {
my ($self, #args) = #_;
return $self->_dump_response($self->SUPER::_post(#args));
}
sub _dump_response {
my ($self, $response) = #_;
warn Data::Dumper::Dump([$response->decoded_content], [qw(content)]);
return $response;
}
package main;
my $client = JSON::RPC::InstrumentedClient->new();
my $url = 'http://localhost:19000';
... # rest of check_ac.pl
This wraps the calls to _get and _post that JSON::RPC::Client makes internally in such a way as to let you examine what the web server actually said in response to the request we made. The above code dumps the text content of the page; this might not be the right thing in your case and will blow up if an error is encountered. It's a debugging aid only, to help you figure out from the client code side what is wrong with the server.
That's enough caveats for now, I think. Good luck.
It seems to be a bug in method new of JSON::RPC::ReturnObject.
sub new {
my ($class, $obj, $json) = #_;
my $content = ( $json || JSON->new->utf8 )->decode( $obj->content );
#...
# line 193
$content->{error} ? $self->is_success(0) : $self->is_success(1);
#...
}
$content's value will be something returned from a JSON::decode() call. But looking at the documentation, it seems that JSON->decode() returns a scalar which could be a number, a string, an array reference, or a hash reference.
Unfortunately, JSON::RPC::ReturnObject->new() doesn't check what sort of thing JSON->decode() returned before trying to access it as a hashref. Given your error, I'm going to go ahead and assume what it got in your case was not one. :-)
I don't know if there's a way to force a fix from your code. I'd recommend contacting the author and letting him know about the issue, and/or filing a bug.

Perl and Complex SOAP Request

I need to make a somewhat complex soap query using Perl, preferably using SOAP::Lite. I know the service is active and have been successful in getting errors back from the other end. Here is the soap query I need to make:
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<GetCategories xmlns="http://webservices.uship.com">
<token>string</token>
</GetCategories>
</soap:Body>
</soap:Envelope>
I've researched this via Google to no avail.
Update: The code used so far is
use SOAP::Lite;
print SOAP::Lite
-> uri('webservices.uship.com/uShipsvc.asmx?WSDL';)
-> proxy('http:/webservices.uship.com')
-> GetCategories('myToken')
-> result;
This returns
500 bad hostname, 500 Can't connect to :80 (Bad hostname '') at soap2.pl line 2
From SOAP::Lite's Getting Started Guide your code should look something like:
#!perl -w
use SOAP::Lite;
print SOAP::Lite
uri('http://www.soaplite.com/Temperatures')
proxy('http://webservices.uship.com')
GetCategories('string')
result;
Plug in the URI for the returned object in uri()
I had issues making SOAP calls because the server that I was talking to was .NET, which apparently has communication problems with SOAP::Lite:
http://msdn.microsoft.com/en-us/library/ms995764.aspx#soapliteperl_topic3
Even if your server isn't .NET, this is another way to make your call (that works for me):
# proxy and uri strings should NOT have trialing slashes
my $_uri = 'http://youruri.com/whatever';
my $_proxy = 'http://yourproxy.com/something.asmx';
my $methodName = 'GetCategories';
my #params = (
SOAP::Data->name( 'token'=>'string' ),
);
my $handle = SOAP::Lite
->uri( $_uri )
->proxy( $_proxy , timeout => 30, keep_alive => 1 )
->on_action( sub{ $_uri . "/" . $_[1] } );
my $method = SOAP::Data
->name( $methodName )
->attr( {xmlns => $_uri . "/"} );
my $rv = $handle->call( $method=>#params );
if( $rv->fault() ){
print "SOAP Error ($methodName) :: " . $handle->transport()->status() . "\n\t" . $rv->faultcode() . ": " . $rv->faultstring();
} else {
print $rv->result();
}
Also, looking at your comment to one of the answers
codeuse SOAP::Lite; print SOAP::Lite ->
uri('webservices.uship.com/uShipsvc.asmx?WSDL';) ->
proxy('http:/webservices.uship.com') -> GetCategories('myToken') ->
result;
You might have the uri and proxy backwards. I.e., the proxy should be your .asmx (without the "?WSDL"). If you want to you the ?WSDL, it's a completely different method of connecting than using the uri+proxy. See: http://guide.soaplite.com/#access%20with%20service%20description%20%28wsdl%29
You need to correct your URIs, with http:/webservices.uship.com I get 500 No Host option provided at test-soap.pl line 7. Change it to this:
use SOAP::Lite;
print SOAP::Lite
-> uri('http://webservices.uship.com/uShipsvc.asmx?WSDL')
-> proxy('http://webservices.uship.com')
-> GetCategories('myToken')
-> result;
Consider using SOAP::Trace to trace the execution of SOAP calls
You can include this use statement in your lib/script:
use SOAP::Lite +trace => [qw/ debug method fault /];
This can help you debug your SOAP call.

Adding authHeader to Perl SOAP::Lite request

I am having some trouble creating a request to this WSDL that works; it requires authHeaders and I am not having much luck adding them. This is what I am trying:
# make proxy for the service
my $soap = SOAP::Lite->service($wsdl);
# add fault hanlder
$soap->on_fault(
sub { # SOAP fault handler
my $soap = shift;
my $res = shift;
# Map faults to exceptions
if(ref($res) eq '') {
die($res);
}
else {
die($res->faultstring);
}
return new SOAP::SOM;
}
);
# authentication request headers
my #headers = (
SOAP::Header->name('user')->value('myemail#whatever.com')->uri($apins),
SOAP::Header->name('password')->value('mypassword')->uri($apins),
SOAP::Header->name('appName')->value('TestApp')->uri($apins),
SOAP::Header->name('appVersion')->value('0.02')->uri($apins)
);
# request method
print $soap->getCompanyInfo('NB', #headers);
The response I get when doing this is:
String value expected instead of SOAP::Header reference
The method I am requesting has two string parameters, both optional. And suggestions?
I was able to get help form the SOAP::Lite mailing list. If I want to pass my own headers, I have to use the call method instead of the actually method name.
# create header for requests
my $authHeader = SOAP::Header->name("xsd:authHeader" =>
\SOAP::Header->value(
SOAP::Header->name('xsd:user')->value($s7user)->type(''),
SOAP::Header->name('xsd:password')->value($s7pass)->type(''),
SOAP::Header->name('xsd:appName')->value('TestApp')->type(''),
SOAP::Header->name('xsd:appVersion')->value('0.03')->type('')
));
# create data to pass as method paramaters
my $params = SOAP::Data->name('ns:email')->value($s7user)->type('');
# request method
$soap->call('checkLogin', $params, $authHeader);
In order to use the call method, you will need to define a proxy (endpoint) on your soap object. Hope this is helpful for someone else down the road.