我需要在myServer上为login登录c#代码。 我尝试使用此代码,但myServer总是以相同的响应回复我 (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;
}
当我尝试使用Google Chrome应用邮递员或 Arc 连接到服务器时,登录成功。
我的代码中的错误在哪里?
答案 0 :(得分:0)
为了解决这个问题,我使用了 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());
}