c# - 通过 SSL 使用 HttpWebRequest 发送请求时出现错误 502(错误的网关)

标签 c# ssl httpwebrequest system.net.webexception

我在经典 ASP 中有以下代码片段,用于发送命令并通过 SSL 检索响应:

Dim xmlHTTP
Set xmlHTTP = Server.CreateObject("Msxml2.ServerXMLHTTP.3.0")
xmlHTTP.open "POST", "https://www.example.com", False
xmlHTTP.setRequestHeader "Content-Type","application/x-www-form-urlencoded"
xmlHTTP.setRequestHeader "Content-Length", Len(postData)
xmlHTTP.Send postData
If xmlHTTP.status = 200 And Len(message) > 0 And Not Err Then
   Print xmlHTTP.responseText
End If

然后我用了this code作为在 c# 中重新实现请求的引用:

private static string SendRequest(string url, string postdata)
{
   WebRequest rqst = HttpWebRequest.Create(url);
   // We have a proxy on the domain, so authentication is required.
   WebProxy proxy = new WebProxy("myproxy.mydomain.com", 8080);
   proxy.Credentials = new NetworkCredential("username", "password", "mydomain");
   rqst.Proxy = proxy;
   rqst.Method = "POST";
   if (!String.IsNullOrEmpty(postdata))
   {
       rqst.ContentType = "application/x-www-form-urlencoded";

       byte[] byteData = Encoding.UTF8.GetBytes(postdata);
       rqst.ContentLength = byteData.Length;
       using (Stream postStream = rqst.GetRequestStream())
       {
           postStream.Write(byteData, 0, byteData.Length);
           postStream.Close();
       }
   }
   ((HttpWebRequest)rqst).KeepAlive = false;
   StreamReader rsps = new StreamReader(rqst.GetResponse().GetResponseStream());
   string strRsps = rsps.ReadToEnd();
   return strRsps;
}

问题是,在调用 GetRequestStream 时,我不断收到 WebException 消息 “远程服务器返回错误:(502) Bad Gateway。”

一开始以为是SSL证书校验的问题。所以我添加了这一行:

ServicePointManager.CertificatePolicy = new AcceptAllCertificatePolicy();

在哪里

public class AcceptAllCertificatePolicy : ICertificatePolicy
{
    public bool CheckValidationResult(ServicePoint srvPoint, 
                                      System.Security.Cryptography.X509Certificate certificate,
                                      WebRequest request, 
                                      int certificateProblem)
    {
        return true;
    }
}

而且我不断收到相同的 502 错误。有什么想法吗?

最佳答案

读取错误响应的实体主体。它可能会提示正在发生的事情。

执行此操作的代码如下:

catch(WebException e)
{
if (e.Status == WebExceptionStatus.ProtocolError)
{
    WebResponse resp = e.Response;
    using(StreamReader sr = new StreamReader(resp.GetResponseStream()))
    {
         Response.Write(sr.ReadToEnd());
    }
}
}

这应该显示错误响应的全部内容。

关于c# - 通过 SSL 使用 HttpWebRequest 发送请求时出现错误 502(错误的网关),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2159361/

相关文章:

c# - 在 asp SqlDataSource 中定义 ConnectionString

c# - WPF MVVM Bind Dictionary<String, List<String>> 到数据网格

c# - 单元测试与键选择器和比较器不同

python - Postgres - python 多个 SSL 连接

c# - 如何使用 C# 连接到路由器 "panel"

c# - 如何解析多部分 HttpWebResponse

c# - DrawLine 方法提供比 DrawLines 方法更高的质量

php - 安全页面上的 Symfony 链接

Android 证书固定与公钥固定

ruby - 我可以通过 http 下载名称中包含空格的文件吗? ( ruby )