简体   繁体   English

在C#中使用WebClient发布数据和服务器重播Bad Gateway

[英]Post data using WebClient in C# and server replay Bad Gateway

I need to write c# code for Login at myServer. 我需要在myServer上编写用于登录的C#代码。 I try with this code, but myServer reply me always with the same response (502) Bad Gateway 我尝试使用此代码,但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;
        }

When I try to connect to server with the Google Chrome App Postman or Arc , the Login have successful. 当我尝试使用Google Chrome App PostmanArc连接到服务器时,登录成功。

Where is the error in my code? 我的代码中的错误在哪里?

For resolve this problem I had used the HttpWebResponse class instead of WebClient . 为了解决此问题,我使用了HttpWebResponse类而不是WebClient

This is the finally code 这是最后的代码

        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());
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM