Windows phone 8 在Schedule/Background Agent中发送httpwebrequest
我正试图从Windows phone 8 在Schedule/Background Agent中发送httpwebrequest,windows-phone-8,httpwebrequest,windows-phone,webrequest,background-agents,Windows Phone 8,Httpwebrequest,Windows Phone,Webrequest,Background Agents,我正试图从后台代理发送http web请求。代码如下。json\u回调从未被触发,我的请求也没有到达服务器。我已经完成了所有的异常处理,没有一个被触发 如何在后台代理中发送web请求 protected override void OnInvoke(ScheduledTask task) { string toastMessage = "Testing Push running."; ShellToast toast = new ShellToas
后台代理发送http web请求
。代码如下。json\u回调
从未被触发,我的请求也没有到达服务器。我已经完成了所有的异常处理,没有一个被触发
如何在后台代理中发送web请求
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();
}
不确定这是否对您有帮助,但以下是我如何在后台代理中发出HTTP请求:
使用WebClient
进行调用(这是在非常好的HttpClient NuGet包可用之前编写的):
\u event.WaitOne()
将冻结您正在等待的当前线程-因此它永远不会完成。就个人而言,我会使用async/await重新编写postTokenToServer
方法,并使用WebClient()
,更干净,代码更少。这就是我想要的,对吗?我不希望主bg任务线程在收到响应之前退出。为什么webclient应该用于webrequest任务?使用webclient
可以消除回调的需要并简化代码,也可以等待,但我需要发出post req。@MilanAggarwal只需将代码更改为使用UploadDataAsync。在这种情况下,我如何才能添加标头信息,以便我的服务器能够正确地对其进行身份验证?
public async Task<string> GetArrivalsAsync( IEnumerable<int> locations )
{
var request = new WebClient();
var requestUri = GetArrivalsRequestUri( locations );
var response = await request.DownloadStringTask( requestUri );
return response;
}
/// <summary>
/// The WebClientExtensions class provides extension methods for the <see cref="System.Net.WebClient"/> class.
/// </summary>
public static class WebClientExtensions
{
/// <summary>
/// This extension method is used to asynchronously download data from a URI
/// and return that data in the form of a string.
/// </summary>
/// <param name="webClient">The <see cref="System.Net.WebClient"/> instance used to perform the download.</param>
/// <param name="uri">The URI to download data from.</param>
/// <returns>The <see cref="Task"/> used to perform the operation.</returns>
public static Task<string> DownloadStringTask( this System.Net.WebClient webClient, Uri uri )
{
if ( uri == null )
{
throw new ArgumentNullException( "uri" );
}
var tcs = new TaskCompletionSource<string>();
webClient.DownloadStringCompleted += ( s, e ) =>
{
if ( e.Error != null )
{
tcs.SetException( e.Error );
}
else
{
tcs.SetResult( e.Result );
}
};
webClient.DownloadStringAsync( uri );
return tcs.Task;
}
}