Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/272.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 通过SSL发送带有HttpWebRequest的请求时出现错误502(坏网关)_C#_Ssl_Httpwebrequest_System.net.webexception - Fatal编程技术网

C# 通过SSL发送带有HttpWebRequest的请求时出现错误502(坏网关)

C# 通过SSL发送带有HttpWebRequest的请求时出现错误502(坏网关),c#,ssl,httpwebrequest,system.net.webexception,C#,Ssl,Httpwebrequest,System.net.webexception,我在classic 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" xmlHTT

我在classic 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
然后,我使用c#中的引用来重新实现请求:

问题是,在调用GetRequestStream时,我一直收到一个WebException,消息是“远程服务器返回了一个错误:(502)坏网关。”

起初,我认为这与SSL证书验证有关。所以我加了一行:

ServicePointManager.CertificatePolicy = new AcceptAllCertificatePolicy();
在哪里


我不断地得到相同的502错误。有什么想法吗?

web服务的wsdl可能正在与域名和SSL证书“争论”。IIS将使用IIS注册的域名(默认情况下是本地域上的机器名,不一定是您的web域)自动生成web服务的WSDL。如果证书域与SOAP12地址中的域不匹配,您将收到通信错误。

读取错误响应的实体正文。它可能暗示了正在发生的事情

执行此操作的代码如下所示:

catch(WebException e)
{
if (e.Status == WebExceptionStatus.ProtocolError)
{
    WebResponse resp = e.Response;
    using(StreamReader sr = new StreamReader(resp.GetResponseStream()))
    {
         Response.Write(sr.ReadToEnd());
    }
}
}
这应该显示错误响应的全部内容。

我得到了问题的更详细描述:代理返回消息:“用户代理无法识别”,因此我手动设置它。另外,我将代码更改为use(),如前所述。最终工作代码如下所示

private static string SendRequest(string url, string postdata)
{
    if (String.IsNullOrEmpty(postdata))
        return null;
    HttpWebRequest rqst = (HttpWebRequest)HttpWebRequest.Create(url);
    // No proxy details are required in the code.
    rqst.Proxy = GlobalProxySelection.GetEmptyWebProxy();
    rqst.Method = "POST";
    rqst.ContentType = "application/x-www-form-urlencoded";
    // In order to solve the problem with the proxy not recognising the user
    // agent, a default value is provided here.
    rqst.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)";
    byte[] byteData = Encoding.UTF8.GetBytes(postdata);
    rqst.ContentLength = byteData.Length;

    using (Stream postStream = rqst.GetRequestStream())
    {
        postStream.Write(byteData, 0, byteData.Length);
        postStream.Close();
    }
    StreamReader rsps = new StreamReader(rqst.GetResponse().GetResponseStream());
    string strRsps = rsps.ReadToEnd();
    return strRsps;
}
用户代理丢失

例如:
request.UserAgent=“Mozilla/4.0(兼容;MSIE 7.0;Windows NT 5.1)”

这种情况发生在我身上,因为如果Java应用程序没有及时响应,远程机器上的Java代理会超时请求,这使得.NET默认超时变得毫无用处。以下代码循环遍历所有异常并写出响应,帮助我确定它实际上来自代理:

static void WriteUnderlyingResponse(Exception exception)
{
    do
    {
        if (exception.GetType() == typeof(WebException))
        {
            var webException = (WebException)exception;
            using (var writer = new StreamReader(webException.Response.GetResponseStream()))
                Console.WriteLine(writer.ReadToEnd());
        }
        exception = exception?.InnerException;
    }
    while (exception != null);
}
代理的响应主体如下所示:

<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>502 Proxy Error</title>
</head><body>
<h1>Proxy Error</h1>
<p>The proxy server received an invalid
response from an upstream server.<br />
The proxy server could not handle the request <em><a href="/xxx/xxx/xxx">POST&nbsp;/xxx/xxx/xxx</a></em>.<p>
Reason: <strong>Error reading from remote server</strong></p></p>
</body></html>

502代理错误
代理错误
代理服务器接收到无效的消息
来自上游服务器的响应。
代理服务器无法处理该请求。 原因:从远程服务器读取时出错


非常好的建议!通过这个,我发现了更多关于这个问题的信息,并提出了一个解决方案。谢谢。这显示了我以前无法获得的大量服务器信息。
static void WriteUnderlyingResponse(Exception exception)
{
    do
    {
        if (exception.GetType() == typeof(WebException))
        {
            var webException = (WebException)exception;
            using (var writer = new StreamReader(webException.Response.GetResponseStream()))
                Console.WriteLine(writer.ReadToEnd());
        }
        exception = exception?.InnerException;
    }
    while (exception != null);
}
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>502 Proxy Error</title>
</head><body>
<h1>Proxy Error</h1>
<p>The proxy server received an invalid
response from an upstream server.<br />
The proxy server could not handle the request <em><a href="/xxx/xxx/xxx">POST&nbsp;/xxx/xxx/xxx</a></em>.<p>
Reason: <strong>Error reading from remote server</strong></p></p>
</body></html>