C# 使用 HttpWebRequest 通过 SSL 发送请求时出现错误 502(错误网关)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2159361/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Error 502 (Bad Gateway) when sending a request with HttpWebRequest over SSL
提问by Leonardo
I have the following snippet in classic ASP, to send a command and retrieve the response over SSL:
我在经典 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
Then I used this codeas a reference to reimplement the request in c#:
然后我用这段代码作为参考,在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;
}
The problem is, when calling GetRequestStream I keep getting a WebException with the message "The remote server returned an error: (502) Bad Gateway."
问题是,在调用 GetRequestStream 时,我不断收到带有消息的 WebException "The remote server returned an error: (502) Bad Gateway."
At first I thought it had to do with the SSL certificate verification. So I added this line:
起初我以为这与SSL证书验证有关。所以我添加了这一行:
ServicePointManager.CertificatePolicy = new AcceptAllCertificatePolicy();
Where
在哪里
public class AcceptAllCertificatePolicy : ICertificatePolicy
{
public bool CheckValidationResult(ServicePoint srvPoint,
System.Security.Cryptography.X509Certificate certificate,
WebRequest request,
int certificateProblem)
{
return true;
}
}
And I keep getting the same 502 error. Any ideas?
而且我不断收到相同的 502 错误。有任何想法吗?
采纳答案by Leonardo
With the help of thisI got a more detailed description of the problem: The proxy was returning the message: "The user agent is not recognized." So I set it manually. Also, I changed the code to use GlobalProxySelection.GetEmptyWebProxy(), as described here. The final working code is included below.
在此帮助下,我得到了更详细的问题描述:代理返回消息:“无法识别用户代理。” 所以我手动设置。另外,我改变了代码,使用GlobalProxySelection.GetEmptyWebProxy(),如所描述这里。最终的工作代码包含在下面。
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;
}
回答by Joel Etherton
It is possible that the wsdl for the web service is "arguing" with the domain name and the SSL certificate. IIS will autogenerate a web service's WSDL using the IIS registered domain name (which by default is the machine name on the local domain, not necessarily your web domain). If the certificate domain doesn't match the domain in the SOAP12 Address you will receive communication errors.
Web 服务的 wsdl 可能与域名和 SSL 证书“争论”。IIS 将使用 IIS 注册的域名(默认情况下是本地域上的机器名称,不一定是您的 Web 域)自动生成 Web 服务的 WSDL。如果证书域与 SOAP12 地址中的域不匹配,您将收到通信错误。
回答by feroze
Read the entity body of the error response. It might have a hint as to what is happening.
读取错误响应的实体正文。它可能暗示正在发生的事情。
The code to do that is as follows:
执行此操作的代码如下:
catch(WebException e)
{
if (e.Status == WebExceptionStatus.ProtocolError)
{
WebResponse resp = e.Response;
using(StreamReader sr = new StreamReader(resp.GetResponseStream()))
{
Response.Write(sr.ReadToEnd());
}
}
}
That should show the full contents of the error response.
那应该显示错误响应的完整内容。
回答by Jishnu Sukumaran
UserAgent is missing
缺少用户代理
for example : request.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)";
例如: request.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)";
回答by Alexandru
This was happening for me because a Java proxy on the remote machine was timing out requests if the Java application did not respond in time, rendering the .NET default timeouts kind of useless. The following code loops through all exceptions and writes out responses which helped me determine it was actually coming from the proxy:
这发生在我身上,因为如果 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);
}
The response body from the proxy looked something like this:
来自代理的响应正文如下所示:
<!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 /xxx/xxx/xxx</a></em>.<p>
Reason: <strong>Error reading from remote server</strong></p></p>
</body></html>