我正在使用一个简单的HttpWebRequest包装器,它在所有情况下返回一个字符串:如果回答没问题,它会返回应答字符串,如果出错,它会返回String.Empty。
public async Task<string> FireAsync(string method, string postData, string url)
{
httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.Method = method; // HttpMethod
httpWebRequest.Accept = "application/json"; // ;odata=verbose
try
{
var response = (HttpWebResponse)await httpWebRequest.GetResponseAsync();
if (response.StatusCode != HttpStatusCode.OK)
{
return String.Empty;
}
var responseStream = response.GetResponseStream();
var postStreamReader = new StreamReader(responseStream);
string data = await postStreamReader.ReadToEndAsync();
return data ?? String.Empty; // if null, return empty
}
catch (Exception ex)
{
return String.Empty;
}
}
问题是有时会返回空字符串。有时,它会在很长一段时间后返回答案。我在使用WebClient时没有回忆起类似的问题。
还有其他人有相同的经历吗?