此 python servicenow 脚本的 Perl 版本发布文件

Perl version of this python servicenow script posting a file

所以我要查看 ServiceNow 的附件 API,记录在此处: https://docs.servicenow.com/integrate/inbound_rest/reference/r_AttachmentAPI-POST.html

对于我正在处理的应用程序,我需要编写一些 Perl 代码来处理附件。不幸的是,ServiceNow Perl API 库不处理大于 5mb 的附件,因此我需要使用实例附带的库存附件 API。

从上面的 link 中,我看到了关于如何使用此 python 代码 post 文件的示例。

#Need to install requests package for python
#easy_install requests
import requests

# Set the request parameters
url = 'https://instance.service-now.com/api/now/attachment/file?table_name=incident&table_sys_id=d71f7935c0a8016700802b64c67c11c6&file_name=Issue_screenshot.jpg'

# Specify the file To send. When specifying fles to send make sure you specify the path to the file, in
# this example the file was located in the same directory as the python script being executed.
data = open('Issue_screenshot.jpg', 'rb').read()

# Eg. User name="admin", Password="admin" for this code sample.
user = 'admin'
pwd = 'admin'

# Set proper headers
headers = {"Content-Type":"image/jpeg","Accept":"application/json"}

# Do the HTTP request
response = requests.post(url, auth=(user, pwd), headers=headers, data=data)

# Check for HTTP codes other than 201
if response.status_code != 201: 
    print('Status:', response.status_code, 'Headers:', response.headers, 'Error Response:',response.json())
    exit()

# Decode the JSON response into a dictionary and use the data
data = response.json()
print(data)

我在 posting 中使用了很多 REST::Client,但不幸的是,我找不到一个很好的例子来说明如何处理上述 ^^ 但在 Perl 中。如何使用 REST::Client 到 post 像上面这样的文件?

我已经通过在我的脚本中调用 curl 来解决这个问题,但是使用 REST::Client 会更优雅。

您可以使用 LWP::UserAgent Perl 模块来实现相同的目的:

#!/usr/bin/perl

use strict;
use warnings;
use LWP::UserAgent;
use HTTP::Request;
use Fcntl;
use JSON qw[decode_json];
use Data::Dumper;

my $ua = LWP::UserAgent->new;

my $url = 'https://instance.service-now.com/api/now/attachment/file?table_name=incident&table_sys_id=d71f7935c0a8016700802b64c67c11c6&file_name=Issue_screenshot.jpg';

my $user = 'admin';
my $pwd = 'admin';

$ua->credentials( 'instance.service-now.com', '<REALM>', $user, $pwd);

my $file = 'Issue_screenshot.jpg';

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

$request->header( 'Content-Type' => 'image/jpeg');
$request->header( 'Accept' => 'application/json');
$request->header( 'Content-Length' => -s $file);

sysopen(my $fh,$file,O_RDONLY);

$request->content( sub {
    sysread($fh,my $buf,1024);

    return $buf;
});

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

unless($res->code == 201) {
    print 'Status: '.$res->code, 'Headers:',$res->headers_as_string,'Error Response:',$res->content;
    exit;
}

my $data = decode_json($res->content);

print Dumper($data);