mikes300 has asked for the wisdom of the Perl Monks concerning the following question:

I have a web service i am submitting an xml file (using nettool currently to submit it). Having a hard time sending the request via perl HTTP. I am thinking that i might need to serialize the xml file, then send it over however a bit amiss at how to accomplish this. This is what i have so far, and based this on a simple POST script that does work. The nettool request using the url in the script and the contents of the test.xml file works perfect and i get a 200 response with data. I keep getting 400 bad request here...
#!/usr/bin/perl -w use strict; use FileHandle; use LWP::UserAgent; use HTTP::Request; sub printFile($) { my $fileHandle = $_[0]; while (<$fileHandle>) { my $line = $_; chomp($line); print "$line\n"; } } my $fh = new FileHandle; $fh->open("</home/test.xml") or die "Could not open file\n"; printFile($fh); $fh->close(); # automatically closes file; my $userAgent = LWP::UserAgent->new(); my $request = HTTP::Request->new(POST => 'http://test.com:7080/b2b?msg +Fmt=testRequest'); $request->header('Host' => "test.com:7080"); $request->content($fh); $request->content_type("text/xml; charset=utf-8"); my $response = $userAgent->request($request); if($response->code == 200) { print $response->as_string; } else { print $response->error_as_HTML; } #

Replies are listed 'Best First'.
Re: Sending xml message in perl
by Jenda (Abbot) on Dec 05, 2008 at 23:39 UTC

    First you open a file, read all the data there is, close the filehandle and then pass that filehandle to some method. That doesn't look right.

    Second, not everything has to be an object for gawd's sake.

    open my $fh, '<', '/home/test.xml' or die "Could not open file\n"; printFile($fh); close $fh;

    Third, don't use prototypes. They are not what you think. It's not a way to ensure a subroutine receives a certain number of parameters, it's a way to create a subroutine that is parsed in some special way, more or less similar to some builtin.

    Four, the printFile() is way too complicated. Why do you read the line into $_ and then copy to $line. Either read it directly to $line or keep on using $_. Also why chomp off the newline and append it again?

    sub printFile { my $fh = $_[0]; while (<$fh>) { print $_; } }

Re: Sending xml message in perl
by Crackers2 (Parson) on Dec 05, 2008 at 23:25 UTC

    You're reading the whole file and closing the filehandle before you pass it to $request->content, so that method won't actually add anything.

    Try either removing the printFile and $fh->close() calls, or re-opening $fh before you pass it to $request->content.