【问题标题】:Post data using WebClient in C# and server replay Bad Gateway在 C# 中使用 WebClient 发布数据并服务器重放 Bad Gateway
【发布时间】:2017-03-06 00:31:26
【问题描述】:

我需要在 myServer 上为 Login 编写 c# 代码。 我尝试使用此代码,但 myServer 总是以相同的响应回复我 (502) 网关错误

        ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, errors) => true;
        string result = "";
        string json = "{\"UserName\": \"myUser\", \"Password\": \"myPassword\"}";

        using (var client = new WebClient())
        {
            client.Headers[HttpRequestHeader.ContentType] = "application/json";
            client.Encoding = Encoding.UTF8;
            result = client.UploadString("https://<myServer>/Login", "POST", json;
        }

当我尝试使用 Google Chrome 应用程序 PostmanArc 连接到服务器时,登录成功。

我的代码中的错误在哪里?

【问题讨论】:

  • 没有任何关于服务器如何工作的规范,并且期望数据很难帮助您

标签: c# post webclient


【解决方案1】:

为了解决这个问题,我使用了 HttpWebResponse 类而不是 WebClient

这是最后的代码

        HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create("https://myserver");
        using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
        {
            string json = new JavaScriptSerializer().Serialize(new
            {
                UserName = "<myUserName>",
                Password = "<myPassword>"
            });
            streamWriter.Write(json);
        }

        var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
        using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
        {
            Console.WriteLine(streamReader.ReadToEnd());
        }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-12-05
    • 2019-02-26
    • 2021-02-15
    • 2015-07-19
    • 2021-09-11
    • 2018-01-20
    • 2017-05-10
    • 2022-07-14
    相关资源
    最近更新 更多