On Sep 5, 2011, at 10:07 AM, Octavian Rasnita wrote: > I have tried to use 2 scripts which I think should do similar things, but the > first one is working, while the second is not. Can you make some light and > tell me what's the difference between them and why the second is not working? > > 1. The first: > > use LWP::UserAgent; > > my $ua = LWP::UserAgent->new; > my $req = HTTP::Request->new( POST => 'http://localhost/cgi-bin/post.pl' ); > $req->header( content_type => 'application/json' ); > $req->content( 'some json content' ); > my $res = $ua->request( $req ); > print $req->as_string; > print $res->as_string; > > 2. The second: > > use LWP::UserAgent; > > my $ua = LWP::UserAgent->new; > my $res = $ua->post( 'http://localhost/cgi-bin/post.pl', Content => 'some > json content' );
This line is a no-op--you are changing a request header *after* the request has already been sent: > $res->request->header( content_type => 'application/json' ); The default content-type is application/x-www-form-urlencoded, AFAIK, which mean that the content you are sending may appear invalid to the CGI module and may be ignored. What happens when you instead do: my $res = $ua->post( 'http://localhost/cgi-bin/post.pl', Content => 'json=some%20json%20content' ); ? Keary Suska > print $res->request->as_string; > print $res->as_string; > > > The file post.pl: > #!/usr/bin/perl > > use strict; > use CGI; > > my $query = CGI->new; > my $data = $query->param('POSTDATA'); > > print "Content-Type: text/html\n\n"; > print "Content: $data\n"; > > > The first gives the following result: > > POST http://localhost/cgi-bin/post.pl > User-Agent: libwww-perl/6.02 > Content-Type: application/json > > some json content > HTTP/1.1 200 OK > Connection: close > Date: Mon, 05 Sep 2011 15:58:17 GMT > Server: Apache/2.2.15 (Win32) mod_perl/2.0.4-dev Perl/v5.10.1 > Content-Type: text/html > Client-Date: Mon, 05 Sep 2011 15:58:17 GMT > Client-Peer: 127.0.0.1:80 > Client-Response-Num: 1 > Client-Transfer-Encoding: chunked > > Content: some json content > > > While the second gives the following result: > > POST http://localhost/cgi-bin/post.pl > User-Agent: libwww-perl/6.02 > Content-Length: 17 > Content-Type: application/json > > some json content > HTTP/1.1 200 OK > Connection: close > Date: Mon, 05 Sep 2011 16:00:10 GMT > Server: Apache/2.2.15 (Win32) mod_perl/2.0.4-dev Perl/v5.10.1 > Content-Type: text/html > Client-Date: Mon, 05 Sep 2011 16:00:10 GMT > Client-Peer: 127.0.0.1:80 > Client-Response-Num: 1 > Client-Transfer-Encoding: chunked > > Content: > > So it doesn't print the POSTed content, because it doesn't seem to send that > content, although $res->request->as_string shows that it sends it.