我正在制作一个应用程序,以在特定时间间隔后通过网络异步发送我的 Windows 8 Phone 的电池电量。我正在使用DispatcherTimer
for call 在某个特定时间间隔后发送电池电量。
DispatcherTimer timer = new DispatcherTimer(); //Create the timer instance
timer.Interval = TimeSpan.FromSeconds(15); //Set the timer interval
timer.Tick += SendAsyncRequest; //Call this procedure after the time ends
timer.Start();
我想使用 POST 请求发送我的电池电量。
void SendAsyncRequest(object sender, object e)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://192.168.2.17/android_connect/add_device.php");
request.Method = "POST";
request.BeginGetRequestStream(new AsyncCallback(SendBatteryLevel), request);
}
现在,我发送实际请求 ( ) 的代码的核心SendBatteryLevel
如下:
void SendBatteryLevel(IAsyncResult asynchronousResult)
{
HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
using (Stream postStream = request.EndGetRequestStream(asynchronousResult))
{
string username = "CoolSops";
string deviceId = "WindowsPhone";
string batteryLevel = Windows.Phone.Devices.Power.Battery.GetDefault().RemainingChargePercent.ToString();
string post_param = "username=" + username + "&device_id=" + deviceId + "&battery_level=" + batteryLevel;
try
{
byte[] requestBody = System.Text.Encoding.UTF8.GetBytes(post_param);
postStream.Write(requestBody, 0, requestBody.Length);
SendingStatus.Text = "Battery data sent";
postStream.Close();
}
catch (Exception e)
{
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
ErrorStatus.Text = e.ToString();
});
Console.WriteLine(e.Message + "\n\n" + e.Source + "\n\n" + e.StackTrace);
}
}
}
在哪里SendingStatus
和ErrorStatus
是TextBlock
s。当我执行此代码时,我得到一个System.UnauthorizedAccessException
. 异常详情如下:
A first chance exception of type 'System.UnauthorizedAccessException' occurred in System.Windows.ni.dll
An exception of type 'System.UnauthorizedAccessException' occurred in System.Windows.ni.dll and wasn't handled before a managed/native boundary
我不明白我试图以未经授权的方式访问什么。谁能说出为什么会这样?
注意:我在调试程序时注意到了一件有趣的事情。当从方法SendBatteryLevel
调用方法SendAsyncRequest
时,从控件执行几行后SendBatteryLevel
返回SendAsyncRequest
。我试图找出控制返回的确切行数,SendAsyncRequest
但每次都不同。因此,在方法SendBatteryLevel
完全执行之前,该方法会以这种方式被调用两次或有时三次。可能这就是导致异常发生的原因。