POST 请求内容类型 multipart/form-data 下载文件

POST request with multipart/form-data content type to download a file

有一个网页在表单内包含一个按钮。单击该按钮会发出 POST 请求并下载 CSV 文件。

我正在尝试使用 LWP::UserAgent 自动执行 CSV 下载过程。

我从 Chrome 开发者工具中注意到 Content-Typemultipart/form-data; boundary=---WebKitFormBoundary....

知道如何发送 Request Payload 开发者工具正在显示的确切信息吗?

我通常会针对 x-www-form-urlencoded 内容类型执行以下操作。但是我不知道如何提交多部分表单数据。

my $ua = LWP::UserAgent->new;
$ua->cookie_jar({ file => "cookie.txt", autosave => 1});


my $request = HTTP::Request->new('POST', $url);

#copy the form_data from chrome developer tools
my $form_data = 'key=val&key2=val2';

#the form_data is too big (and is in parts) in case of multipart content type

$request->content($form_data);
$request->header('Content-Type' => "application/x-www-form-urlencoded");
#I'll have to use `multipart/form-data; boundary=---WebKitFormBoundary....`

#add some other headers like 'Origin', 'Host' and 'Referer' in similar manner
#...
#...

push @{ $ua->requests_redirectable }, 'POST';

my $response = $ua->request($request);

#Get the file

查看 the documentation for HTTP::Request::Common

POST 上的条目

您可以通过传递 Content_Type => 'form-data'

的伪 header 值来生成 multipart/form-data 请求(而不是 application/x-www-form-urlencoded

看起来像这样

my $response = $ua->post(
    $url,
    Content_Type => 'form-data',
    {
        ...;  # Hash of form key/value pairs
    }
);