在可移植类库中,我有以下将数据发布到特定 URL 的方法。该方法效果很好。但是我想指定一个更激进的超时(默认为 100 秒)。
考虑到可移植类库中的 HttpWebRequest 类上没有 Timeout 属性,如果调用时间超过几秒钟,如何确保调用被放弃?
public async Task<HttpResponse> PostAsync(Uri uri, string data)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
using (Stream requestStream = await request.GetRequestStreamAsync())
{
byte[] postBytes = Encoding.UTF8.GetBytes(data);
requestStream.Write(postBytes, 0, postBytes.Length);
}
HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync();
return new HttpResponse(response.StatusCode, await new StreamReader(response.GetResponseStream()).ReadToEndAsync());
}