在 Perl 中设置 http 请求中的 json 字符串

问题描述 投票:0回答:1

以下 Perl 代码会生成如下所示的错误:

use strict;
use Data::Dumper;
use LWP::UserAgent;
use JSON;

my $token = 'my token';
my $ua = LWP::UserAgent->new;
my $req = HTTP::Request->new(PUT => "endpoint");
$req->header( 'Authorization' => "Bearer $token" );
$req->content_type('application/json');
$req->content('{"text":"whiteboard"}');
 
my $res = $ua->request($req);     
if ($res->is_success) {
    my $content = $res->decoded_content;
    my $fromjson = from_json($content);
    print Dumper $fromjson->{'results'}; 
}
else {
    print $res->status_line, "\n";
    print $res->content, "\n";
}

错误:

 {"detail":[{"loc":["body"],"msg":"str type expected","type":"type_error.str"}]}

但是,如果我用 Python 编写相同的代码,它就可以工作:

import requests
import os
import json

url = 'endpoint'
token='my token'

headers = {
            "Authorization": "Bearer "+token[:-1],
            "Content-type" : "application/json"
            }
res=requests.put(url, json='{"text":"whiteboard"}', headers=headers)
#res=requests.put(url, json='test string', headers=headers) # this also works
print('Response Content:\n',res)

我在 Perl 代码中缺少什么?

python rest perl put
1个回答
0
投票

我相信 Perl 正在发送 JSON 对象

{"text":"whiteboard"}
。 Python 正在发送 JSON 字符串
"{\"text\":\"whiteboard\"}"

端点需要一个 JSON 字符串,因此只有 Python 代码可以工作。


在 Perl 代码中,

$req->content('{"text":"whiteboard"}')
仅发送字符串
{"text":"whiteboard"}
作为正文。

在 Python 代码中,

res=requests.put(url, json='{"text":"whiteboard"}', headers=headers)
将字符串
{"text":"whiteboard"}
编码为 JSON。消息正文是单个 JSON 字符串
"{\"text\":\"whiteboard\"}"

来自文档....

json –(可选)要在请求正文中发送的 JSON 可序列化 Python 对象。

如果你想发送一个 JSON 对象,你可以向它传递一个 Python 字典。

res=requests.put(url, json={"text":"whiteboard"}, headers=headers)

这应该会导致同样的错误。

© www.soinside.com 2019 - 2024. All rights reserved.