首页 > 解决方案 > 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

我试过了:

可悲的是没有上述工作。

这是我的 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#winformsresthttpwebrequest

解决方案


推荐阅读