c# - HttpWebResponse GetResponse 超时
问题描述
我的问题与这个主题非常相似,但是我尝试了不同版本的 .Net Framework,但仍然无法正常工作:
Machine-Specific HttpWebResponse Timeout
在我的程序中,我有一个登录功能来向POST
服务器发送命令。每次我启动程序时,POST
命令总是超时。一旦超时消息弹出,再次点击登录,POST命令可以成功发送到服务器端。但在我的 2 个不同的虚拟机(操作系统:Win7Pro CHT/Win7Pro CHS)中没有问题。
我的开发环境:Windows 7 Pro CHS、.Net Framework 4.7.2
我试过了:
- 放
myRequest.Timeout
- 使用
System.Net.Http
和HttpClient
- 放
myRequest.ServicePoint.Expect100Continue = false
- 设置
myRequest.Abort()
和myResponse.Close()
- 安装
.Net Framework 4.5.2
,4.7.2
和4.8.0
可悲的是没有上述工作。
这是我的 POST 函数:
public string SendPostCommand(string url, string data)
{
try
{
byte[] postBytes = Encoding.GetEncoding("utf-8").GetBytes(data);
HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(url);
myRequest.ContentLength = postBytes.Length;
myRequest.Method = "POST";
myRequest.Timeout = 500;
myRequest.Headers.Add("userKey", "--------------------");
myRequest.ContentType = "application/json";
Stream newStream = myRequest.GetRequestStream();
newStream.Write(postBytes, 0, postBytes.Length);
newStream.Close();
// Get response
using (HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse())
// --------------------------------- ALWAYS HANG HERE
{
using (StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.GetEncoding("utf-8")))
{
string content = reader.ReadToEnd();
myRequest.Abort();
myResponse.Close();
reader.Close();
return content;
}
}
}
catch (System.Exception ex)
{
return null;
}
}
这是我调用函数的方式:
private void btnLogin_Click(object sender, EventArgs e)
{
Dictionary<string, string> dataDict = new Dictionary<string, string>();
dataDict.Add("UserName", txtUsername.Text);
dataDict.Add("UserPassword", txtPwd.Text);
string url = frmMain.g_authAddress + "SysUser/Login";
try
{
string response = SendPostCommand(url, ConvertDictToString(dataDict));
HttpResponse responseObj = JsonConvert.DeserializeObject<HttpResponse>(response);
switch (responseObj.code)
{
case 0:
MessageBox.Show("Login success.");
frmMain.g_CurrentUser = txtUsername.Text;
frmMain.g_isProgramReady = true;
this.Close();
break;
case 1:
MessageBox.Show("User non-exist.");
break;
case 2:
MessageBox.Show("Machine non-exist.");
break;
case 3:
MessageBox.Show("User has no access.");
break;
case 4:
MessageBox.Show("Incorrect password");
break;
default:
MessageBox.Show(responseObj.ErMsg);
break;
}
}
catch (Exception err)
{
MessageBox.Show(err.Message);
}
}
我也尝试过使用httpclient
但仍然失败。不确定这是否是评论者提到的方式turn SendPostCommand() into an async method and await the result
private string testPost(string url, string content)
{
HttpClient client = new HttpClient() { BaseAddress = new Uri(url) };
client.DefaultRequestHeaders.Add("userKey", "--------------------");
HttpContent contentPost = new StringContent(content, Encoding.UTF8, "application/json");
HttpResponseMessage response = client.PostAsync("SysUser/Login", contentPost).GetAwaiter().GetResult();
response.EnsureSuccessStatusCode();
return response.Content.ReadAsStringAsync().GetAwaiter().GetResult();
}
解决方案
推荐阅读
- c++ - 打印一个排序的向量列表
- coq - 归一化(归一化 n)=归一化(n)
- database - TigerGraph 建模:“复合”顶点可能吗?
- node.js - 在帖子中动态引用 Mongodb 用户模式
- r - 根据观察值是否出现在初始 DF 的每个变量下创建布尔 DF
- postgresql - docker-entrypoint.sh 忽略 /docker-entrypoint-initdb.d/my.backup
- react-native-reanimated - 如何撤消 react-native-gesture-handler
- node.js - 尝试在嵌入字段中添加 Discord.js 随机变量时出错
- python - pandas DataFrame中布尔数组的逐行总和
- ios - 将新的 UITextView 分配为第一响应者时如何防止键盘降低