Search code examples
perlperl-modulemod-perllwp

LWP::useragent keep_alive not working


I am using below code to post JSON data using LWP::useragent. I want to keep my session open and post two requests but it seems that its not working on linux machine (two POST requests are sent in two sessions instead of one).

Any suggestions? thanks in advance

#!/usr/bin/perl

use warnings;
use LWP::UserAgent;
use HTTP::Request::Common;

open (JSON, "json3.txt") or die "$!";
$raw_string1 = do{ local $/ = undef; <JSON>; 
};



my $req = HTTP::Request->new(POST => 'http://www.example.com');


$hdr1 = 'User-Agent';
$val1 = 'Java/1.7.0_45';

$hdr2 = 'Connection';
$val2 = 'keep-alive';

$hdr3 = 'Accept';
$val3 = 'application/json, application/*+json';

$hdr4 = 'Host';
$val4 = 'example.com';

$hdr5 = 'Content-Type';
$val5 = 'application/json;charset=UTF-8';


$req -> header($hdr3 => $val3);
$req -> header($hdr5 => $val5);
$req -> header($hdr1 => $val1);
$req -> header($hdr4 => $val4);
$req -> header($hdr2 => $val2);



$req->content_type("application/json");

$req->content("$raw_string1");

my $ua = LWP::UserAgent->new(keep_alive => 1);
$res = $ua->request($req);
print $res->content;
$res = $ua->request($req);
print $res->content; 

Solution

  • its resolved...it wasn't due to backend server closing the connection. i think i was using old perl (5.10) with old fedora version. I spun a new instance of CentOs and its working on it. thanks