c# - 尝试在 C# 中使用 HttpClient 的现有实例时出现异常
问题描述
更新-通过为 HttpClientHandler 设置代理解决了以下问题。但我仍然想知道第一个请求如何在没有设置代理的情况下成功?为什么只有后续请求(在第一个请求之后)会因为代理而失败?
我有一个简单的类可以在不同的请求中重用“HttpClient”的单个实例。我面临的问题是只有第一次调用成功,而所有后续调用都失败并出现 SocketException。
public class MyHttpClient
{
private static readonly HttpClient client;
static MyHttpClient()
{
client = new HttpClient();
client.BaseAddress = new Uri("http://x.com");
}
public async Task<string> GetSecurityToken(LoginData data)
{
var reqMsg = JsonConvert.SerializeObject(data);
var reqContent = new StringContent(reqMsg, System.Text.Encoding.UTF8, "application/json");
var response= await client.PostAsync("/api/v1/security/token", reqContent)
var result = await response.Content.ReadAsStringAsync();
return result
}
}
// The above class is consumed as
var client = new MyHttpClient();
var login = new LoginData("abc@gmail.com", "xxxx");
var result = await client.GetSecurityToken(login); // this call succeeds !
var result1 = await client.GetSecurityToken(login); // this call fails with an exception, but why?
我在第二次通话中遇到的异常是 - SocketException: A connection attempt failed because the connected party did not proper response after a period of time, or established connection failed because connected host has failed to response
解决方案
推荐阅读
- excel - 为什么在此代码期间激活了我的屏幕键盘数字锁定?
- ubuntu - Nginx- 98: Address already in use, Failed to bind to ports 433 and 80
- javascript - CSS / XPATH 选择器查询
- c++ - 在函数中创建多个 lock_guard
- c#-8.0 - 如何转换 IList
到 IList 在 C# 8 中可以为空的引用类型 - c - 执行未从 exec 返回
- c# - 我们可以取消次要视图的 UWP 应用的合并事件吗?
- tensorflow - Talos - 导入 talos - 无法导入名称“tf_utils”
- django - 码头工人 mariadb 和 django
- botframework - 使用 Postman 来自我的本地机器人的 400 错误请求