使用mod-perl 2获取http POST请求的正文 [英] Getting the body of an http POST request, using mod-perl 2

查看:177
本文介绍了使用mod-perl 2获取http POST请求的正文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个快速脚本来修改已提交的文件,并将该内容返回给用户.

I am writing a quick script to munge a submitted file, and return that content to the user.

我的测试代码如下:

#!/path/to/bin/perl
use strict;
use warnings;
use utf8;

use Apache2::RequestRec;
use Apache2::RequestIO; 

my ( $xmlin, $accepts ) = (q{}, q{});
my $format = 'json';

# read the posted content
while (
    Apache2::RequestIO::read($xmlin, 1024)
      ) {};

{
  no warnings;
  $accepts = $Apache2::RequestRec::headers_in{'Accepts'};
}
if ($accepts) {
  for ($accepts) {
    /application\/xml/i && do {
      $format = 'xml';
      last;
    };
    /text\/plain/i && do {
      $format = 'text';
      last;
    };
  } ## end for ($accepts)
} ## end if ($accepts)
print "format: $format; xml: $xmlin\n";

此代码无法使用Undefined subroutine &Apache2::RequestIO::read

如果我注释了while循环,则代码可以正常运行.

If I comment out the while loop, the code runs fine.

不幸的是,Apache2::RequestIO代码是通过Apache2::XSLoader::load __PACKAGE__;插入的,所以我无法检查实际代码....但我不明白为什么这不起作用

Unfortunately the Apache2::RequestIO code is pulled in via Apache2::XSLoader::load __PACKAGE__; so I can't check the actual code.... but I don't understand why this doesn't work

(是的,我也尝试过$r->read(...),无济于事)

(and yes, I've also tried $r->read(...), to no avail)

推荐答案

我也使用Apache2::RequestIO读取正文:

sub body {
    my $self =  shift;

    return $self->{ body }   if defined $self->{ body };
    $self->apr->read( $self->{ body }, $self->headers_in->get( 'Content-Length' ) );

    $self->{ body };
}

在这种情况下,您应该将原始 Apache2::Request 子类化. .特别注意our @ISA = qw(Apache2::Request);

In this case you should subclass original Apache2::Request. Especially pay attention to our @ISA = qw(Apache2::Request);

我不知道为什么,但是标准的body方法返回了我:

I do not know why, but standard body method return me:

$self->body        # {}
$self->body_status # Missing parser

Content-Typeapplication/json时.所以我以这种方式解决.然后自己解析身体:

when Content-Type is application/json. So I work around that in such way. Then parse body myself:

sub content {
    my $self =  shift;

    return   $self->{ content }   if defined $self->{ content };

    my $content_type =  $self->headers_in->get('Content-Type');
    $content_type =~ s/^(.*?);.*$/$1/;

    return   unless exists $self->{ $content_type };

    return $self->{ content } =  $self->{ $content_type }( $self->body, $self );
}

其中:

use JSON;
sub new {
    my ($proto, $r) = @_;

    my $self = $proto->SUPER::new($r);
    $self->{ 'application/json' } =  sub {
        decode_json shift;
    };
    return $self;
}

这篇关于使用mod-perl 2获取http POST请求的正文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆