我正在尝试http web request
从background agent
. 代码如下。永远不会被触发,我的json_Callback
请求没有到达服务器。我已经完成了所有的异常处理,并且没有一个被触发。
如何在后台代理发送网络请求?
protected override void OnInvoke(ScheduledTask task)
{
string toastMessage = "Testing Push running.";
ShellToast toast = new ShellToast();
toast.Title = "Background Agent Sample";
toast.Content = toastMessage;
toast.Show();
try
{
string token = "no token";
appSettings.TryGetValue("newToken", out token);
toastMessage = "New Push running.";
toast = new ShellToast();
toast.Title = "Background Agent Sample";
toast.Content = token;
toast.Show();
if (!String.IsNullOrEmpty(token))
postTokenToServer(token);
_event = new ManualResetEvent(false);
_event.WaitOne();
}
catch (Exception e)
{
toastMessage = e.Message;
toast = new ShellToast();
toast.Title = "a";
toast.Content = toastMessage;
toast.Show();
}
#if DEBUG_AGENT
ScheduledActionService.LaunchForTest(
task.Name, TimeSpan.FromSeconds(1));
#endif
toast = new ShellToast();
toast.Title = "task complete";
toast.Show();
NotifyComplete();
}
private void postTokenToServer(string token)
{
ShellToast toast = new ShellToast();
toast.Title = "is net available";
toast.Content = System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable().ToString();
toast.Show();
if (System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable())
{
HttpWebRequest req = HttpWebRequest.Create(new Uri(BASE + "/account/device")) as HttpWebRequest;
req.Headers["Cookie"] = "user=" + appSettings["token"] + ";uid=" + (string)appSettings["uid"];
toast.Title = "Cookies token";
toast.Content = (string)appSettings["token"];
toast.Show();
toast.Title = "uid";
toast.Content = (string)appSettings["uid"];
toast.Show();
req.Method = "POST";
req.ContentType = "application/json";
req.BeginGetRequestStream(new AsyncCallback(setParams_Callback), req);
}
else
_event.Set();
}
private void setParams_Callback(IAsyncResult result)
{
string uri = "no token";
appSettings.TryGetValue("newPushToken", out uri);
var req = (HttpWebRequest)result.AsyncState;
Stream postStream = req.EndGetRequestStream(result);
JObject data = new JObject();
data.Add("dev_token", uri);
data.Add("dev_type", "windows");
ShellToast toast = new ShellToast();
toast.Title = "Posting Now";
toast.Content = data.ToString(Newtonsoft.Json.Formatting.None);
toast.Show();
using (StreamWriter sw = new StreamWriter(postStream))
{
string json = data.ToString(Newtonsoft.Json.Formatting.None);
sw.Write(json);
}
postStream.Close();
try
{
req.BeginGetResponse(new AsyncCallback(json_Callback), req);
}
catch(Exception e)
{
toast.Title = "Posting Error";
toast.Content =e.Message;
toast.Show();
_event.Set();
}
toast.Title = "Posted";
toast.Content = DateTime.UtcNow.ToShortTimeString();
toast.Show();
}
private void json_Callback(IAsyncResult result)
{
ShellToast toast = new ShellToast();
toast.Title = "completed";
toast.Show();
_event.Set();
}