Pergunta

Eu tenho o seguinte snippet no ASP clássico, para enviar um comando e recuperar a resposta sobre o 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

Então eu usei este código Como referência para reimplementar a solicitação em 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;
}

O problema é que, ao chamar getRequestStream, continuo recebendo uma WebException com a mensagem "The remote server returned an error: (502) Bad Gateway."

No começo, pensei que isso tinha a ver com a verificação do certificado SSL. Então eu adicionei esta linha:

ServicePointManager.CertificatePolicy = new AcceptAllCertificatePolicy();

Onde

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

E continuo recebendo o mesmo erro 502. Alguma ideia?

Foi útil?

Solução 2

Com a ajuda disso Recebi uma descrição mais detalhada do problema: o proxy estava retornando a mensagem: "O agente do usuário não é reconhecido. "Então eu defino manualmente. Além disso, mudei o código para usar GlobalProxySelection.getEmptyWebProxy(), conforme descrito aqui. O código de trabalho final está incluído abaixo.

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

Outras dicas

Leia o corpo da entidade da resposta de erro. Pode ter uma dica sobre o que está acontecendo.

O código a fazer isso é o seguinte:

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

Isso deve mostrar o conteúdo completo da resposta de erro.

É possível que o WSDL para o serviço da Web esteja "argumentando" com o nome de domínio e o certificado SSL. O IIS irá autogerear automaticamente o WSDL de um serviço da web usando o nome de domínio registrado do IIS (que por padrão é o nome da máquina no domínio local, não necessariamente o seu domínio da Web). Se o domínio do certificado não corresponder ao domínio no endereço SOAP12, você receberá erros de comunicação.

UserAgent está faltando

Por exemplo: request.UserAgent = "Mozilla/4.0 (compatível; MSIE 7.0; Windows NT 5.1)";

Isso estava acontecendo para mim, porque um proxy Java na máquina remota estava divulgando solicitações se o aplicativo Java não respondesse a tempo, renderizando o tempo limite padrão do .NET meio inútil. Os seguintes códigos percorrem todas as exceções e escrevem respostas que me ajudaram a determinar que ele realmente vem do proxy:

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

O corpo de resposta do proxy parecia algo assim:

<!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>
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top