[英]Web request from HttpClient stuck
I created http request with HttpClient class.I want to make GET request to some url.我用 HttpClient 类创建了 http 请求。我想向某个 url 发出 GET 请求。 For example " http://www.google.com ", or another url.
例如“ http://www.google.com ”或其他网址。
My application hosted in Amazon EC2 and use .Net Core 2.2.我的应用程序托管在 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);
}
}
I don't know why, but my request stuck in client.GetAsync.我不知道为什么,但我的请求卡在 client.GetAsync 中。 After that nothing happens, without any response or exceptions.
之后什么都没有发生,没有任何响应或异常。 It is very strangely, because I can see this behavior only on Amazon EC2 instance.
这很奇怪,因为我只能在 Amazon EC2 实例上看到这种行为。 In my local machine this request successfully run.
在我的本地机器上,这个请求成功运行。 When I use Postman or Chrome on EC2 machine and create the same request - I receive response.
当我在 EC2 机器上使用 Postman 或 Chrome 并创建相同的请求时 - 我收到响应。 If i replace HttpClient to WebRequest - I have the same behavior.
如果我将 HttpClient 替换为 WebRequest - 我有相同的行为。
Thank you in advance先感谢您
Minimal reproducible example for Console App:控制台应用程序的最小可重现示例:
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);
}
}
}
Instead of代替
HttpClientRequestAsync().GetAwaiter().GetResult();
use this:用这个:
Task.Run(async () => await HttpClientRequestAsync());
Disabling proxy when i created HttpClient helped me: UseProxy = false;创建 HttpClient 时禁用代理对我有帮助:UseProxy = false; Proxy = null;
代理 = 空;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.