如何从CGI Perl中的POST主体获取URLencoded数据

时间:2013-05-30 21:26:03

标签: perl cgi mime-types

POSTDATA不是正确的答案。我已经阅读了文档但仍然没有看到我如何获取数据。

我想收到这个请求:

POST /cgi-bin/myscript.cgi HTTP/1.1
Host: myhost.com
Content-Length: 3
Content-Type: application/x-www-form-urlencoded

255

让服务器响应 您发送了字符串“255”

请协助,我是Perl的初学者,并且对这个看似简单的请求得到了一堆看似错误和无用的答案。

3 个答案:

答案 0 :(得分:1)

CGI会自动解析表单数据,因此您需要隐藏您所获得的表单数据(或至少声称是)。

use CGI qw( );
$ENV{CONTENT_TYPE} = 'application/octet-stream';
my $cgi = CGI->new();
my $post_data = $cgi->param('POSTDATA');

更好的解决方案:让请求者使用正确的内容类型(例如application/octet-stream),或让请求者实际发送表单数据(例如data=255)。

答案 1 :(得分:0)

我的独特解决方案是将客户请求中的ContentType更改为'application / octet-stream'

模块CGI CPAN说:

  

如果POSTed数据的类型不是 application / x-www-form-urlencoded 或    multipart / form-data ,然后将不会处理POSTed数据   而是在名为POSTDATA的参数中按原样返回。

因此,如果您无法将客户请求更改为其他ContentType,则不会对其进行处理。

答案 2 :(得分:-1)

CGI(至少在最近的版本中)会将错误编码的x-www-form-urlencoded参数填充到名为keywords的参数中。最好发送一个合适的内容类型,然后POSTDATA的工作方式与文档说的完全相同:

  

如果POSTed数据不属于application / x-www-form-urlencoded或   multipart / form-data,然后将不处理POSTed数据...

use strictures;
use CGI::Emulate::PSGI;
use Plack::Test;
use HTTP::Request::Common;
use Test::More;

my $post = POST "/non-e-importa",
    "Content-Length" => 5,
    "Content-Type" => "application/x-www-form-urlencoded",
    Content => "ohai\n";

my $cgis = CGI::Emulate::PSGI->handler( sub {
    use CGI "param", "header";
    my $incorrectly_encoded_body = param("keywords");
    print header("text/plain"), $incorrectly_encoded_body;
});

test_psgi $cgis, sub {
    my $cb  = shift;
    my $res = $cb->($post);
    is $res->content, "ohai", "Soopersek437 param: keywords";
};

done_testing();

__END__
prove so-16846138 -v
ok 1 - Soopersek437 param: keywords
1..1
ok
All tests successful.
Result: PASS