Beefy Boxes and Bandwidth Generously Provided by pair Networks
The stupid question is the question not asked

content type in LWP::UserAgent

by BernieC (Pilgrim)
on Nov 16, 2022 at 22:53 UTC ( #11148205=perlquestion: print w/replies, xml ) Need Help??

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

I know this is a dumb question but I'm lost in a maze of twisty passages going back and forth between LWP::UserAgent and HTTP::Request::Common. I have a very simple question. I need to send a POST with the body being JSON data and I understand {I think} that to make that play nice with the server I should have a "content-type: application/json" header ... it should be trivial but I can't figure out where to stick that information in the $ua->POST() call. I must be missing something obvious.

Replies are listed 'Best First'.
Re: content type in LWP::UserAgent
by choroba (Cardinal) on Nov 16, 2022 at 23:51 UTC
    According to the documentation, this should work (and if I understand the output, it really does).
    #!/usr/bin/perl use warnings; use strict; use LWP::UserAgent; use Cpanel::JSON::XS qw{ encode_json }; my $ua = 'LWP::UserAgent'->new(timeout => 1); my $response = $ua->post('', 'content-type' => 'application/json', Content => encode_json({key => 'value'})); print $response->decoded_content;

    map{substr$_->[0],$_->[1]||0,1}[\*||{},3],[[]],[ref qr-1,-,-1],[{}],[sub{}^*ARGV,3]

      I can unequivocally say that what choroba has there works properly. Here's an actual working example I just tested (with some name/data modifications):

      use warnings; use strict; use LWP::UserAgent; use JSON; my $ua = LWP::UserAgent->new; my $body_content = { token => 'NTE2M2Q3YmFmMGEzNjEzMGQyZmFmYmViNGEasdfmNzkzMTE3NzI3MWMz +MDhkZjliYWE3NTI1OTg1MDQwNjNlZg' }; my $resp = $ua->post( '', 'Content-Type' => 'application/json', 'Content' => encode_json $body_content ); print $resp->decoded_content;

Log In?

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://11148205]
Approved by choroba
Front-paged by Corion
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others contemplating the Monastery: (6)
As of 2023-01-30 12:22 GMT
Find Nodes?
    Voting Booth?

    No recent polls found