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

Hi all, I have a simple script to POST data, but for some reason it is not posting the data:
#!/usr/bin/perl use strict; use LWP::UserAgent; use MIME::Base64; use JSON; my $ua = LWP::UserAgent->new; push @{ $ua->requests_redirectable }, 'POST'; my $server_endpoint = ""; my $server_api_key = "xxxx"; my $encoded = ""; my $req = HTTP::Request->new(POST => $server_endpoint); #$req->header('content-type' => 'multipart/form-data'); $req->header('content-type' => 'application/json'); my $post_json = { key => $server_api_key, source => $encoded, format => "json", }; my $post_data = encode_json($post_json); $req->content($post_data); printf "\n\n$post_data\n"; my $resp = $ua->request($req); print $resp->as_string; if ($resp->is_success) { my $message = $resp->decoded_content; print "Received reply: $message\n"; } else { print "HTTP POST error code: ", $resp->code, "\n"; print "HTTP POST error message: ", $resp->message, "\n"; }
Response in web server logs: - - [03/Apr/2016:19:22:43 +1000] "POST /api/1/upload/ HT +TP/1.1" 301 424 "-" "libwww-perl/6.08"
You can see that the data is not being posted? I would expect to see something like: (which works when I use the Paw Client to do the POST) - - [03/Apr/2016:19:32:44 +1000] "POST /api/1/upload/?key +=xxxx&format=json& HTT +P/1.1" 200 2570 "-" "Paw/2.3.3 GCDHTTPRequest"
Any ideas would be greatly appreciated. Thanks, HW

Replies are listed 'Best First'.
Re: LWP not POSTING (400 Bad Request)
by haukex (Archbishop) on Apr 03, 2016 at 11:01 UTC

    Hi HollyWould,

    From your example log message, it looks to me like the parameters key, source and format are supposed to be encoded into the URI - whether or not they're also part of the POST body I can't tell, you'd have to take a look at the traffic (e.g. Wireshark) and tell us more about that.

    It's been a while since I used raw LWP, so I might be forgetting an easier way, but one way to get those parameters onto the URI is with URI:

    # ... use URI; my $uri = URI->new($server_endpoint); $uri->query_form( key => $server_api_key, source => $encoded, format => "json", ); my $req = HTTP::Request->new(POST => $uri); # ...

    This gets me the URL query string ...?key=xxxx& which looks like what you want.

    Hope this helps,
    -- Hauke D

      Hauke - Bingo! Yes, the web application is expecting the attributes in the URI, not in the POST body. Thanks for your assistance with this, much appreciated. Cheers,HW
Re: LWP not POSTING (400 Bad Request)
by Gangabass (Vicar) on Apr 03, 2016 at 10:15 UTC
    Can you post Paw's Headers and Content here?

    The first thing is wrong that you're posting to in your code but to the +=xxxx&format=json&
    from the Paw...

    But the most interesting thing will be POST content from the Paw...

      Hi Gangabass - Thanks for the reply. Yes, the URI is incorrect. This has been corrected. Thanks.