我正在尝试使用HttpClient类获取/发布并面临以下问题
出于某种原因,它会继续自动取消
private static Task<T> HttpClientSendAsync<T>(string url, object data, HttpMethod method, string contentType, CancellationToken token)
{
HttpRequestMessage httpRequestMessage = new HttpRequestMessage(method, url);
RetryDelegatingHandler retryDelegatingHandler = new RetryDelegatingHandler();
retryDelegatingHandler.PreAuthenticate = true;
retryDelegatingHandler.Credentials = Credential;
retryDelegatingHandler.Proxy = null;
HttpClient httpClient = new HttpClient(retryDelegatingHandler);
httpClient.Timeout = new TimeSpan(Constants.TimeOut);
if (data != null)
{
byte[] byteArray = Encoding.ASCII.GetBytes(Helper.ToJSON(data));
MemoryStream memoryStream = new MemoryStream(byteArray);
httpRequestMessage.Content = new StringContent(new StreamReader(memoryStream).ReadToEnd(), Encoding.UTF8, contentType);
}
Task<HttpResponseMessage> httpResponseMessage = httpClient.SendAsync(httpRequestMessage);
httpResponseMessage.ContinueWith((task) =>
{
if (!task.IsFaulted)
{
HttpResponseMessage response = task.Result;
response.Content.ReadAsStringAsync().ContinueWith(
(stringTask) =>
{
if (!stringTask.IsFaulted)
{
return Helper.FromJSON<T>(stringTask.Result);
}
else
{
Logger.Log(string.Format("SendAsyncRequest Task IsFaulted: {0} \nException: {1}", typeof(T), task.Exception));
UpdateError(typeof(T).ToString());
return default(T);
}
});
}
else
{
Logger.Log(string.Format("SendAsyncRequest Task IsFaulted: {0} \nException: {1}", typeof(T), task.Exception));
UpdateError(typeof(T).ToString());
return default(T);
}
});
}
更新:它确实有效,但在尝试处理故障时它仍无法正常工作。
return httpClient.SendAsync(httpRequestMessage).ContinueWith(task =>
{
var response = task.Result;
return response.Content.ReadAsStringAsync().ContinueWith(stringTask =>
{
var json = stringTask.Result;
return Helper.FromJSON<T>(json);
});
}).Unwrap();
答案 0 :(得分:1)
Task.ContinueWith
返回继续任务:Task
或Task<T>
。如果我理解这个问题,在这种情况下你可以这样做:
var continuation = httpResponseMessage.ContinueWith((task) =>
{
if (!task.IsFaulted)
{
HttpResponseMessage response = task.Result;
return response.Content.ReadAsStringAsync().ContinueWith(
(stringTask) =>
{
...
和continuation
最终会成为Task<Task<T>>
,您可以致电.Unwrap()
将其转换为代理任务Task<T>
。