我向电子商务API发出SOAP请求,以了解在给定的时间范围内为指定产品订购了多少订单。
我的方法需要一个产品ID和几天的时间来创建时间范围。然后,它构造一个SOAP请求并返回已售产品的数量。
public static async Task<int?> GetOrdersFromApi(int providedId, int days) {
var dateFrom = DateTime.Now.AddDays(days * -1).ToString("yyyy-MM-dd") + " 00:00:00";
var dateTo = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
float orderedCount = 0;
int orderedCountToPass = 0;
int i = 0;
var binding = new BasicHttpBinding {
MaxReceivedMessageSize = 40000000
};
var address = new EndpointAddress("http://example.com/api/get/");
using (var client = new ApiOrdersPortTypeClient(binding, address)) {
try {
while (true) {
// request parameters
var request = new ApiOrdersGetAsync.requestType {
authenticate = new ApiOrdersGetAsync.authenticateType {
userLogin = "Username",
authenticateKey = "Key",
}
};
request.@params = new ApiOrdersGetAsync.paramsType {
ordersStatuses = new string[] { "finished" },
products = new productType[1],
};
[email protected][0] = new productType {
productIdSpecified = true,
productId = providedId,
};
[email protected] = new ordersRangeType {
ordersDateRange = new ordersDateRangeType()
};
request.@params.ordersRange.ordersDateRange.ordersDateTypeSpecified = true;
[email protected] = ordersDateTypeType.dispatch;
[email protected] = dateFrom;
[email protected] = dateTo;
[email protected] = true;
[email protected] = i;
// processing the result
var results = await client.getAsync(request);
foreach (var result in results.Results) {
int productsResultsPage = 0;
foreach (var product in result.orderDetails.productsResults) {
try {
if (result.orderDetails.productsResults[productsResultsPage ].productId == providedId) {
orderedCount += result.orderDetails.productsResults[y].productQuantity;
productsResultsPage++;
}
} catch (IndexOutOfRangeException ex) {
// error is thrown to escape loop - sloppy, I know
Console.WriteLine(ex);
};
}
};
orderedCountToPass = (int)orderedCount;
orderedCount = 0;
i++;
};
} catch (NullReferenceException) {
// do nothing, we just want to exit while loop when i is higher than page count
}
return orderedCountToPass;
};
}
结果通常应该成百上千,但是不管产品销售的好坏,它都会返回0到4之间的值。
以下是示例响应:
例如,我只对productId == 479
感兴趣,但是对其他我不感兴趣的产品也下了订单-我需要过滤它们。
我在尝试过滤结果方面做错了。如何正确执行?我确定请求是正确的,并且响应中确实包含所有可能的订单。
您正在获取xml结果,因此请使用Net Xml库:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication1
{
class Program
{
const string URL = @"Enter URL Here";
static void Main(string[] args)
{
XDocument doc = XDocument.Load(URL);
List<XElement> items = doc.Descendants("item").ToList();
}
}
}