0

我有一个包含有效 xml 的 url,但不确定如何使用 RestClient 检索它。我以为我可以下载字符串,然后像我已经使用 WebClient 那样解析它。

正在做:

        public static Task<String> GetLatestForecast(string url)
        {
            var client = new RestClient(url);
            var request = new RestRequest();

            return client.ExecuteTask<String>(request);
        }

让 VS 为“字符串”必须是具有公共无参数构造函数的非抽象类型而哭泣。

见执行任务:

namespace RestSharp
{
    public static class RestSharpEx
    {
        public static Task<T> ExecuteTask<T>(this RestClient client, RestRequest request)
            where T : new()
        {
            var tcs = new TaskCompletionSource<T>(TaskCreationOptions.AttachedToParent);

            client.ExecuteAsync<T>(request, (handle, response) =>
            {
                if (response.Data != null)
                    tcs.TrySetResult(response.Data);
                else
                    tcs.TrySetException(response.ErrorException);
            });

            return tcs.Task;
        }
    }
}

感谢 Claus Jørgensen btw 提供了关于动态磁贴的精彩教程!

我只想下载字符串,因为我已经有一个解析器在等待它解析它:-)

4

1 回答 1

1

如果您想要的只是一个字符串,请改用以下方法:

namespace RestSharp
{
    public static class RestSharpEx
    {
        public static Task<string> ExecuteTask(this RestClient client, RestRequest request)
        {
            var tcs = new TaskCompletionSource<string>(TaskCreationOptions.AttachedToParent);

            client.ExecuteAsync(request, response =>
            {
                if (response.ErrorException != null)
                    tcs.TrySetException(response.ErrorException);
                else
                    tcs.TrySetResult(response.Content);
            });

            return tcs.Task;
        }
    }
}
于 2012-03-23T16:07:32.050 回答