在我之前的其他人写了一个程序,需要一堆UPS跟踪#并查询UPS的状态。问题是,随着时间的推移,这个程序变得越来越复杂。这些查询现在花了太长时间。每个查询大约需要350毫秒,有些页面有近40个查询,每页加载大约需要15秒。
该方法将跟踪#作为字符串,然后向UPS发出某种xml请求,返回正确的数据,速度非常慢。
以下是代码:
public static List<string> MakeRequest(string tracking)
{
List<string> res = new List<string>();
string xmlStringRequest = "<?xml version=\"1.0\"?>" +
"<AccessRequest xml:lang=\"en-US\">" +
"<AccessLicenseNumber>apilicense</AccessLicenseNumber>" +
"<UserId>apiusername</UserId>" +
"<Password>apipassword</Password>" +
"</AccessRequest>" +
"<?xml version=\"1.0\"?>" +
"<TrackRequest xml:lang=\"en-US\">" +
"<Request>" +
"<TransactionReference>" +
"<CustomerContext>Your Test Case Summary Description</CustomerContext>" +
"<XpciVersion>1.0</XpciVersion>" +
"</TransactionReference>" +
"<RequestAction>Track</RequestAction>" +
"<RequestOption>1</RequestOption>" +
"</Request>" +
"<TrackingNumber>" + tracking + "</TrackingNumber>" +
"</TrackRequest>";
ASCIIEncoding encodedData = new ASCIIEncoding();
byte[] byteArray = encodedData.GetBytes(xmlStringRequest);
//Create Request
HttpWebRequest wr = (HttpWebRequest)WebRequest.Create("https://onlinetools.ups.com/ups.app/xml/Track");
wr.Method = "POST";
wr.KeepAlive = false;
//wr.ContentType = "application/x-www-form-urlencoded";
wr.ContentLength = byteArray.Length;
XmlDocument xmlDoc = new XmlDocument();
try
{
//Send XML
Stream SendStream = wr.GetRequestStream();
SendStream.Write(byteArray, 0, byteArray.Length);
SendStream.Close();
//Get Response
WebResponse response = wr.GetResponse();
Stream responseStream = response.GetResponseStream();
StreamReader reader = new StreamReader(responseStream);
//Console.Write(reader.ReadToEnd());
xmlDoc.LoadXml(reader.ReadToEnd());
XmlNode nl = xmlDoc.GetElementsByTagName("ResponseStatusCode").Item(0);
response.Close();
if (nl.InnerText == "1")
{
XmlNode del = xmlDoc.GetElementsByTagName("ActivityLocation").Item(0);
XmlNodeList act = del.ChildNodes;
foreach (XmlNode n in act)
{
if (n.Name == "Code")
{
res.Add(n.InnerText);
}
else if (n.Name == "Description")
{
res.Add(n.InnerText);
}
else if (n.Name == "SignedForByName")
{
res.Add(n.InnerText);
}
else
{
continue;
}
}
res.Add(xmlDoc.GetElementsByTagName("Date").Item(0).InnerText);
res.Add(xmlDoc.GetElementsByTagName("Time").Item(0).InnerText);
}
else
{
res.Add("Tracking Info Not Available");
}
}
catch (Exception ex)
{
xmlDoc = null;
}
return res;
}
我介绍了代码,看起来花费最长的是这一行:
SendStream.Write(byteArray, 0, byteArray.Length);
是否有一种明显的方法可以提高此查询的速度/效率?我对jSON比对XML更熟悉。