USPS HTTP发布请求

时间:2018-11-25 00:48:48

标签: perl http

这是我尝试运行以下Perl代码时收到的错误消息。任何想法是什么原因造成的?看来它不喜欢API = Verify,但这是API的唯一名称,该名称返回我可以找到的9位邮政编码。

80040B1AAPI授权失败。这不是有效的API名称 protocol.USPSCOM :: DoAuth

# Perl subroutine for POST Request
#########
sub FindTracking() {
$saddress="60 Passional Way";
$scity="Burnsville";
$szip="27690";
$sstate="NC";
print "start of tracking...<br>";

$queryString = qq~
<?xml version="1.0"?>
https://secure.shippingapis.com/ShippingAPI.dll?API=Verify&XML=        
<AddressValidateRequest USERID="xxxxxxx">
<Revision>1</Revision>
<Address ID="0">
<Address1></Address1>
<Address2>$saddress</Address2>
<City>$scity</City>
<State>$sstate</State>
<Zip5>$szip</Zip5>
<Zip4></Zip4>
</Address>
</AddressValidateRequest>
<?xml version="1.0"?>
<AddressValidateResponse><Address ID="0">
<Address2></Address2><City></City><State></State><Zip5></Zip5>
<Zip4></Zip4></Address></AddressValidateResponse>
<Error>
<Number></Number>
<Source></Source>
<Description></Description>
<HelpFile></HelpFile>
<HelpContext></HelpContext>
</Error>
~;

# Instantiate the user agent and set our agent string
$userAgent = new LWP::UserAgent;
$userAgent->agent( 'USPS' );
$queryString =~ s/ /\%20/ig;
$request = new HTTP::Request( 'POST',      
'https://secure.shippingapis.com/ShippingAPI.dll' );

# Set the content type
$request->content_type( 'text/xml' );

# Set the query string
$request->content( $queryString );

# Make the request
$response = $userAgent->request( $request );
print $response->content();
# Check the status of the request
if ( $response->is_success ) {
    $content = $$response{ "_content" };
  $TrackingNumber = "";
  ($success) = $content =~ /\<AddressValidateRequest\>(.*)\    
 <\/AddressValidateRequest\>/;
  print "<br><br>==>some $content<br>";
  if ($success eq "Success") {
    ($TrackingNumber)= $content =~ /\<Zip4\>(.*)\<\/Zip4\>/;
   print "here with $TrackingNumber<br>";
   }

}
else {
  print "<br><br>here with resp=$response<br>req=$request <br>cont     
$content";
}
}

2 个答案:

答案 0 :(得分:1)

首先,您具有无效的查询字符串。将您的操作与USPS WebTools example进行比较,并删除它们不显示的内容。确保您正确设置了USERID(并且未使用“ xxxxxxx”);那里有一个环境变量。

或者,您可以尝试使用GitHub中的Business::USPS::WebTools模块。它实现了邮政编码查找。

答案 1 :(得分:0)

将查询XML更改为:

$queryString = qq~
<AddressValidateRequest USERID="xxxxxxxxxxx">
<Revision>1</Revision>
  <Address ID="0">
    <Address1></Address1>
    <Address2>$saddress</Address2>
    <City>$scity</City>
    <State>$sstate</State>
    <Zip5>$szip</Zip5>
    <Zip4></Zip4>
  </Address>
</AddressValidateRequest>
~;

然后将请求构建为GET而不是POST:

$userAgent = new LWP::UserAgent;
$userAgent->agent( 'USPS' );
$url = "https://secure.shippingapis.com/ShippingAPI.dll?API=Verify&XML=$queryString";

$request = new HTTP::Request( 'GET',  $url );