如何获取"在 c# 桌面应用程序中调用 API 时使用了多少网络数据(移动或 WiFi(" 我想知道调用 API 服务时如何获取总使用数据
我已经完成了以下代码:
if (!NetworkInterface.GetIsNetworkAvailable())
return;
NetworkInterface[] interfaces
= NetworkInterface.GetAllNetworkInterfaces();
foreach (NetworkInterface ni in interfaces)
{
Console.WriteLine(" Bytes Sent: {0}",
ni.GetIPv4Statistics().BytesSent);
Console.WriteLine(" Bytes Received: {0}",
ni.GetIPv4Statistics().BytesReceived);
lblCarrierCharge.Text = " Bytes Received: " + ni.GetIPv4Statistics().BytesReceived;
}
接口调用
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(cloudEndpoint);
request.Method = "Get";
long inputLength = request.ContentLength;
long outputLength = 0;
string responseContent = "";
DateTime beginTimestamp = DateTime.Now;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
计算每次调用接收的总字节数。您希望保存当前值.GetIPv4Statistics().BytesReceived
,然后在调用后执行相同的调用并将新值减去前一个值。
int previousNetworkBytesSent = 0;
foreach (NetworkInterface ni in interfaces)
{
previousNetworkBytesSent += ni.GetIPv4Statistics().BytesReceived;
}
// perform your call here
int newNetworkBytesSent = 0;
foreach (NetworkInterface ni in interfaces)
{
newNetworkBytesSent += ni.GetIPv4Statistics().BytesReceived;
}
int totalBytesUsed = newNetworkBytesSent - previousNetworkBytesSent;
检查数据类型是否合适,并随意优化。