You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

带--data-raw $符号的Curl转LWP代码报500错误求助

解决GraphQL文件上传的Perl LWP 500错误

问题描述

原curl命令可正常执行GraphQL文件上传操作,但通过工具生成的Perl LWP代码返回500服务器错误。排查确认:移除curl命令--data-raw参数前的$符号会触发同样错误,生成的LWP代码存在$符号处理异常的问题。

问题根源

  1. 生成的LWP代码在multipart表单的起始边界前错误添加了\x24(即$符号),违反了multipart/form-data的格式规范
  2. GraphQL查询字符串中的变量占位符(如$organizationId、$file)被错误转义为\x24organizationId,导致GraphQL服务无法解析查询语句

修复后的Perl代码

使用HTTP::Request::Common模块构建请求,自动处理multipart编码和转义,避免手动拼接原始数据的错误:

#!perl
use strict;
use warnings;

use LWP::UserAgent;
use HTTP::Request::Common;

my $ua = LWP::UserAgent->new( send_te => 0 );

# 定义GraphQL操作内容
my $operations = '{
    "operationName": "UploadImportFile",
    "variables": {"organizationId": "43434", "file": null},
    "query": "mutation UploadImportFile($organizationId: String!, $file: Upload!) {
        uploadImportFile(organizationId: $organizationId, file: $file) {
            uploadStatus
            uploadFileHeaders
            sampleData
            dataLinesCount
            filePath
            __typename
        }
    }"
}';

# 定义文件映射关系
my $map = '{"1": ["variables.file"]}';

# 构建multipart POST请求
my $req = POST 'https://someurl/graphql',
    Content_Type => 'multipart/form-data',
    Content => [
        operations => $operations,
        map        => $map,
        # 文件字段:若需上传实际内容,替换空字符串为文件路径或 scalar_ref => \$file_content
        '1'        => [
            'sample_teacher_one_fresh_v2.csv',
            '',
            'Content-Type' => 'text/csv'
        ]
    ],
    # 添加请求头
    Accept                => 'application/json, text/plain, */*',
    Accept_Language       => 'en-US,en;q=0.9,hi;q=0.8',
    Authorization         => 'Bearer PGTT78yyGLnRJGh...YJ8IF0ZeqzIXT',
    User_Agent            => 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/106.0.0.0 Safari/537.36',
    'Sec-Ch-Ua'           => '"Chromium";v="106", "Google Chrome";v="106", "Not;A=Brand";v="99"',
    'Sec-Ch-Ua-Mobile'    => '?0',
    'Sec-Ch-Ua-Platform'  => '"Linux"',
    'Sec-Fetch-Dest'      => 'empty',
    'Sec-Fetch-Mode'      => 'cors',
    'Sec-Fetch-Site'      => 'same-site';

# 发送请求并输出结果
my $res = $ua->request($req);
print $res->status_line, "\n";
print $res->content, "\n";

关键修复点

  • 借助HTTP::Request::Common::POST自动处理multipart边界、内容编码和特殊字符转义,无需手动拼接原始表单数据
  • 保留GraphQL查询中的$变量占位符,避免错误转义导致服务解析失败
  • 文件字段支持直接传入路径或内容引用,更灵活且不易出错

内容的提问来源于stack exchange,提问作者gYanI

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 14:10:30