0

我正在尝试http web requestbackground 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();
    }
4

1 回答 1

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;
    }
}
于 2013-07-27T14:06:47.867 回答