0

示例代码:

sub record_put :Private {
    my ( $self, $c, @args ) = @_;

    $c->log->info( join ', ', %{ $c->request->headers } ) ;
    $c->log->info( $c->request->body ) ;

    $c->response->body( $c->request->body ) ;
}

这是日志数据:

[info] user-agent, Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/28.0.1500.71 Chrome/28.0.1500.71 Safari/537.36, connection, keep-alive, accept, application/json, text/javascript, */*; q=0.01, accept-language, en-US,en;q=0.8, x-requested-with, XMLHttpRequest, origin, http://localhost:3000, accept-encoding, gzip,deflate,sdch, content-length, 125, host, localhost:3000, ::std_case, HASH(0xaec0ba0), content-type, application/json, referer, http://localhost:3000/test
[info] /tmp/PM2C6FXpcC

以下是文档中的一段文本Catalyst::Request

$req->body

Returns the message body of the request, as returned by HTTP::Body: a string, unless Content-Type is application/x-www-form-urlencoded, text/xml, or multipart/form-data, in which case a File::Temp object is returned.

File::Temp手册页没有帮助。即使“对象”重载了它的字符串化,我也看不到如何提取内容。

4

2 回答 2

1

这是我使用的:

  my $rbody = $c->req->body;
  if ($rbody) {
    # Post requests are stored on the filesystem under certain obscure conditions,                                                                           
    # in which case $rbody is a filehandle pointing to the temporary file      
    if (ref $rbody) {           # a filehandle                                 
      $content = join "", readline($rbody);
      close $rbody;
      unlink "$rbody";  # filehandle stringifies to name of temp file          
    } else {                    # a string                                     
      $content = $rbody;
    }
  }

您从该body方法返回的内容代表一个临时文件,可以将其视为文件句柄或字符串。如果你把它当作一个文件句柄,它会从临时文件中读取;如果像字符串一样使用,它的值是临时文件的名称。我使用了很少见的内置函数readline,它与更常见的<…&gt;运算符相同。

我不指望这else条路会走,但它是防御性的,因为你永远不知道。

2014-06-09 添加:您需要显式关闭;否则代码有文件描述符泄漏。Catalyst 开发人员声称它应该自动清理手柄,但事实并非如此。

于 2014-02-06T19:31:15.200 回答
0

如果您只是想解析 JSON,最新的稳定 Catalyst 有一个方法 'body_data' 可以为您执行此操作(请参阅: http: //www.catalystframework.org/calendar/2013/6

于 2014-01-03T23:14:23.480 回答