Welcome to WebmasterWorld Guest from 54.205.96.97

Forum Moderators: coopster & jatar k & phranque

Timeout on a webservice call

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

5+ Year Member



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 Sep 18, 2007 (gmt 0)

10+ Year Member



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 Sep 26, 2007 (gmt 0)

10+ Year Member



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;
 

Featured Threads

My Threads

Hot Threads This Week

Hot Threads This Month