我正在尝试调用 API url,但当我的代码运行此行时,我会遇到错误:
HttpResponseMessage response = client.GetAsync(new Uri(uri)).Result;
,
这是代码。
public static string SimpleGetAsync(string uri)
{
string result = string.Empty;
try
{
HttpClientHandler handler = new HttpClientHandler()
{
AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate
};
HttpClient client = new HttpClient(handler);
HttpResponseMessage response = client.GetAsync(new Uri(uri)).Result;
result = response.Content.ReadAsStringAsync().Result;
}
catch (Exception ex)
{
LogManager.WriteLogByDate(LogFile.Exception.ToString(), "Error HtmlHelper.SimpleGet (" + uri + ") :" + ex.Message + "\r\nWith stacktrace: " + ex.StackTrace + "\r\n\r\n");
}
return result;
}
这是错误信息
One or more errors occurred. at System.Threading.Tasks.Task`1.GetResultCore(Boolean waitCompletionNotification)
你尝试过制作方法吗
async
public static async Task<string> SimpleGet(string uri)
{
string result = string.Empty;
try
{
HttpClientHandler handler = new HttpClientHandler()
{
AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate
};
HttpClient client = new HttpClient(handler);
HttpResponseMessage response = await client.GetAsync(new Uri(uri)).ConfigureAwait(false);
result = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
}
catch (Exception ex)
{
LogManager.WriteLogByDate(LogFile.Exception.ToString(), "Error HtmlHelper.SimpleGet (" + uri + ") :" + ex.Message + "\r\nWith stacktrace: " + ex.StackTrace + "\r\n\r\n");
}
return result;
}
ConfigureAwait