我在 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 时不记得类似的问题。
其他人有同样的经历吗?