Welcome to WebmasterWorld Guest from 54.224.197.251

Forum Moderators: coopster & jatar k & phranque

Message Too Old, No Replies

Timeout on a webservice call

     
7:42 pm on Sep 18, 2007 (gmt 0)

New User

10+ Year Member

joined:June 5, 2006
posts: 18
votes: 0


I'm currently calling a web service that returns some XML like so:


use HTTP::Request::Common;
use LWP::UserAgent;
use XML::Parser;
use CGI;
use URI::Escape;

my $ua = LWP::UserAgent->new;
my $uri = "http://myWebService.com?param1=" . $gVar1 . "&param=" . $gVar2;

my $req = HTTP::Request::Common::POST( $uri);

my $result = $ua->request( $req );
my $webServiceXML = $result->content;

Is there a way to set some sort of timeout around the call in case the web service is down? Currently if the server the web service is on is down the script just runs and runs eventually coming back with a blank screen. I want to add something like:


if(web service-Call-Time > 10 seconds) {
web service is down, insert exception code here
}

Any ideas?

11:14 pm on Sept 18, 2007 (gmt 0)

Preferred Member

10+ Year Member

joined:Dec 30, 2003
posts: 428
votes: 0


Look at the LWP::UserAgent manpage for the new method

my $ua = LWP::UserAgent->new( { timeout => 10} );
...
my $result = blah

It's been a while, but I think $result will be undef if it times out.

Sean

6:20 am on Sept 26, 2007 (gmt 0)

Junior Member from US 

10+ Year Member

joined:Nov 30, 2002
posts:164
votes: 1


The timeout in LWP doesn't work if the host is unreachable. Use alarm if your OS supports it. Here is (untested) code that should implement both timeouts:

use HTTP::Request::Common; 
use LWP::UserAgent;
use XML::Parser;
use CGI;
use URI::Escape;
my $ua = LWP::UserAgent->new;
$ua->timeout(10);
my $uri = "http://myWebService.com?param1=" . $gVar1 . "&param=" . $gVar2;
my $req = HTTP::Request::Common::POST( $uri);
my $result;
eval {
local $SIG{ALRM} = sub { die "alarm\n" };
alarm(10);
$result = $ua->request($req);
alarm(0);
};
return 'web service is down' if $@ eq "alarm\n";
my $webServiceXML = $result->content;
 

Join The Conversation

Moderators and Top Contributors

Hot Threads This Week

Featured Threads

Free SEO Tools

Hire Expert Members