2010-01-29 26 views
22

tengo el siguiente fragmento de código en ASP clásico, para enviar un comando y recuperar la respuesta a través de SSL:Error 502 (Bad Gateway) al enviar una solicitud con HttpWebRequest sobre 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 

Luego usé this code como reimplementar referencia a la solicitud en 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; 
} 

el problema es que cuando se llama a GetRequestStream me siguen dando un WebException con el mensaje "The remote server returned an error: (502) Bad Gateway."

Al principio pensé que tenía que ver con la verificación del certificado SSL. Por lo que añade esta línea:

ServicePointManager.CertificatePolicy = new AcceptAllCertificatePolicy(); 

Dónde

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

Y sigo obteniendo el mismo error 502. ¿Algunas ideas?

Respuesta

26

With the help of this Obtuve una descripción más detallada del problema: El proxy devolvía el mensaje: "El agente de usuario no se reconoce." Así que lo configuré manualmente. Además, cambié el código para usar GlobalProxySelection.GetEmptyWebProxy(), como se describe here. El código de trabajo final se incluye a continuación.

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; 
} 
1

Es posible que el wsdl para el servicio web esté "discutiendo" con el nombre de dominio y el certificado SSL. IIS generará automáticamente un WSDL de un servicio web utilizando el nombre de dominio registrado de IIS (que de forma predeterminada es el nombre de la máquina en el dominio local, no necesariamente su dominio web). Si el dominio del certificado no coincide con el dominio en la dirección SOAP12, recibirá errores de comunicación.

28

Lea el cuerpo de entidad de la respuesta de error. Puede tener una pista sobre lo que está sucediendo.

El código para hacer esto es como sigue:

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

Esto debería mostrar el contenido completo de la respuesta de error.

+0

Excelente consejo! Usando esto descubrí un poco más sobre el problema y se me ocurrió una solución. Gracias. – Leonardo

1

UserAgent falta

por ejemplo: request.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)";

0

Esto me sucedía porque un proxy de Java en la máquina remota agotaba las solicitudes si la aplicación Java no respondía a tiempo, lo que hacía que los tiempos de espera predeterminados de .NET fueran inútiles. El código siguiente se reproduce a través de todas las excepciones y escribe a cabo las respuestas que ayudó a determinar que fue en realidad proviene de la representación:

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); 
} 

el cuerpo de la respuesta desde el proxy parecía algo como esto:

<!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> 
Cuestiones relacionadas