使用Perl的HTTP多部分响应

e37o9pze  于 2023-03-30  发布在  Perl
关注(0)|答案(1)|浏览(149)

有没有可能像multipart request那样提供HTTP multipart response呢?这个场景是这样的,我想提供一个URL,它带一个EmployeeID的参数,返回的响应应该包括员工的照片,最近的工资单,以及姓名,年龄,地址等信息。接收端不是浏览器。但它会是一个程序,它会得到这个响应,然后再处理它们。你知道怎么做吗?
为了给我的上述问题给予更多信息,我必须提供一个URL给我的朋友,他将以编程方式接收响应。例如:

$response = $ua->request($my_url)

我的应用程序应该不仅用数据来响应,而且用文件来响应!我被要求使它返回多部分响应。

vlju58qv

vlju58qv1#

我把我原来的https://gist.github.com/1391017作为响应。

#!/usr/bin/perl
use strict;
use warnings;

use HTTP::Response;

my $response = HTTP::Response->new(
    200, 'OK', [ 'Content-Type' => 'multipart/form-data' ]
);

$response->protocol('HTTP/1.1');
$response->date(time);
$response->server('Foo/1.0');

my $name = HTTP::Message->new([
    'Content-Type'        => 'text/plain; charset=UTF-8',
    'Content-Disposition' => 'form-data; name="name"',
], 'John Doe');

$response->add_part($name);

my $note = HTTP::Message->new([
    'Content-Type'        => 'text/plain; charset=UTF-8',
    'Content-Disposition' => 'form-data; name="note"',
], <<'NOTE');
Resources:
  o http://search.cpan.org/dist/HTTP-Message/lib/HTTP/Message.pm
  o http://search.cpan.org/dist/HTTP-Message/lib/HTTP/Response.pm
  o http://tools.ietf.org/html/rfc2388
  o http://tools.ietf.org/html/rfc2616
NOTE

$response->add_part($note);

my $blob = HTTP::Message->new([
    'Content-Type'        => 'application/octet-stream',
    'Content-Disposition' => 'form-data; name="blob"; filename="blob.bin"',
]);
$blob->add_content('a chunk');
$blob->add_content(' of data');

$response->add_part($blob);

print $response->as_string;

输出:

HTTP/1.1 200 OK
Date: Thu, 24 Nov 2011 10:03:25 GMT
Server: Foo/1.0
Content-Type: multipart/form-data; boundary=xYzZY

--xYzZY
Content-Type: text/plain; charset=UTF-8
Content-Disposition: form-data; name="name"

John Doe
--xYzZY
Content-Type: text/plain; charset=UTF-8
Content-Disposition: form-data; name="note"

Resources:
  o http://search.cpan.org/dist/HTTP-Message/lib/HTTP/Message.pm
  o http://search.cpan.org/dist/HTTP-Message/lib/HTTP/Response.pm
  o http://tools.ietf.org/html/rfc2388
  o http://tools.ietf.org/html/rfc2616

--xYzZY
Content-Type: application/octet-stream
Content-Disposition: form-data; name="blob"; filename="blob.bin"

a chunk of data
--xYzZY--

相关问题