在Schedule / Background Agent中发送httpwebrequest

时间:2013-07-24 11:58:38

标签: windows-phone-8 httpwebrequest windows-phone webrequest background-agents

我正在尝试从http web request发送background agent。代码如下。 json_Callback永远不会被触发,我的请求也无法到达服务器。我已经完成了所有异常处理,但没有一个被触发。

如何在后台代理中发送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();
    }

1 个答案:

答案 0 :(得分:0)

不确定这是否对您有所帮助,但这是我在后台代理中发出HTTP请求的方式:

使用WebClient进行呼叫(这是在非常好的HttpClient NuGet包可用之前编写的):

    public async Task<string> GetArrivalsAsync( IEnumerable<int> locations )
    {
        var request     = new WebClient();
        var requestUri  = GetArrivalsRequestUri( locations );
        var response    = await request.DownloadStringTask( requestUri );

        return response;
    }

请注意,我在这里使用async / await关键字,这极大地简化了编写异步代码的过程。大部分工作都是在WebClient的扩展方法中完成的。我不能赞成扩展方法,但它已经有一段时间了,我不记得我发现它的位置(虽然它可能在StackOverflow上):

/// <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;
    }
}