来自 HttpClient 的 Web 请求卡住了
Web request from HttpClient stuck
我用 HttpClient 创建了 http 请求 class.I 想向某些 url 发出 GET 请求。例如“http://www.google.com”,或另一个 url.
我的应用程序托管在 Amazon EC2 中并使用 .Net Core 2.2。
static HttpClient client = new HttpClient();
private static async Task HttpClientRequestAsync(string url)
{
try
{
var response = await client.GetAsync(url);
string responseJson = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseJson);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
不知道为什么,我的请求卡在了 client.GetAsync。之后什么都没有发生,没有任何响应或异常。这很奇怪,因为我只能在 Amazon EC2 实例上看到这种行为。在我的本地机器上这个请求成功 运行。当我在 EC2 机器上使用 Postman 或 Chrome 并创建相同的请求时 - 我收到了响应。如果我将 HttpClient 替换为 WebRequest - 我有相同的行为。
提前致谢
控制台应用程序的最小可重现示例:
class Program
{
static void Main(string[] args)
{
HttpClientRequestAsync().GetAwaiter().GetResult();
Console.ReadLine();
}
static HttpClient client = new HttpClient();
private static async Task HttpClientRequestAsync()
{
try
{
Console.WriteLine("Your url:");
var url = Console.ReadLine();
var response = await client.GetAsync(url);
string responseJson = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseJson);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
}
创建 HttpClient 时禁用代理帮助了我:
使用代理=假;
代理=空;
而不是
HttpClientRequestAsync().GetAwaiter().GetResult();
使用这个:
Task.Run(async () => await HttpClientRequestAsync());
我用 HttpClient 创建了 http 请求 class.I 想向某些 url 发出 GET 请求。例如“http://www.google.com”,或另一个 url.
我的应用程序托管在 Amazon EC2 中并使用 .Net Core 2.2。
static HttpClient client = new HttpClient();
private static async Task HttpClientRequestAsync(string url)
{
try
{
var response = await client.GetAsync(url);
string responseJson = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseJson);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
不知道为什么,我的请求卡在了 client.GetAsync。之后什么都没有发生,没有任何响应或异常。这很奇怪,因为我只能在 Amazon EC2 实例上看到这种行为。在我的本地机器上这个请求成功 运行。当我在 EC2 机器上使用 Postman 或 Chrome 并创建相同的请求时 - 我收到了响应。如果我将 HttpClient 替换为 WebRequest - 我有相同的行为。
提前致谢
控制台应用程序的最小可重现示例:
class Program
{
static void Main(string[] args)
{
HttpClientRequestAsync().GetAwaiter().GetResult();
Console.ReadLine();
}
static HttpClient client = new HttpClient();
private static async Task HttpClientRequestAsync()
{
try
{
Console.WriteLine("Your url:");
var url = Console.ReadLine();
var response = await client.GetAsync(url);
string responseJson = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseJson);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
}
创建 HttpClient 时禁用代理帮助了我: 使用代理=假; 代理=空;
而不是
HttpClientRequestAsync().GetAwaiter().GetResult();
使用这个:
Task.Run(async () => await HttpClientRequestAsync());