Riccardo Suprani Riccardo Suprani - 9 months ago 110
C# Question

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

I need to write c# code for Login at myServer.
I try with this code, but myServer reply me always with the same response
(502) Bad Gateway

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.

Where is the error in my code?

Answer Source

For resolve this problem I had used the HttpWebResponse class instead of 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>"

        var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
        using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))