简体   繁体   中英

c# HTTP 400 error (Bad Request) thrown by HttpWebRequest (intermitent)

I have a problem with a Web Service. From a Web Method I call this other method to make an HTTP request. What I need to do is to get an XML response from an URL and process it. This is the code where I make the HTTP request:

    private XmlDocument makeHTTPrequest(string url, string parametersStr)
    {
        HttpWebRequest WebReq = (HttpWebRequest)WebRequest.Create(url);

        byte[] buffer = Encoding.ASCII.GetBytes(parametersStr);
        Stream sAnswer = null;
        XmlDocument xDoc = new XmlDocument();
        string proxyAddress = "";
        int proxyPort = 0;
        int requestTimeout = 0;

        try
        {
            proxyAddress = ConfigurationSettings.AppSettings["ProxyAddress"];
            proxyPort = Convert.ToInt32(ConfigurationSettings.AppSettings["ProxyPort"]);
            requestTimeout = Convert.ToInt32(ConfigurationSettings.AppSettings["RequestTimeout"]);

            WebReq.Method = "POST";
            WebReq.ContentType = "application/x-www-form-urlencoded";
            WebReq.ContentLength = buffer.Length;

            if (proxyAddress != "0" && proxyPort != 0)
            {
                WebProxy proxy = null;
                proxy = new WebProxy(proxyAddress, proxyPort);
                proxy.UseDefaultCredentials = true;
                WebReq.Proxy = proxy;
            }

            if (requestTimeout != 0)
            {
                WebReq.Timeout = requestTimeout;
            }

            Stream PostData = WebReq.GetRequestStream();
            PostData.Write(buffer, 0, buffer.Length);
            PostData.Close();

            HttpWebResponse WebResp = (HttpWebResponse)WebReq.GetResponse();
            if (WebResp.StatusCode == HttpStatusCode.OK)
            {
                sAnswer = WebResp.GetResponseStream();
                xDoc.Load(sAnswer);
            }
            else
            {
                throw new Exception("No se obtuvo una respuesta satisfactoria del servidor\r\nHTTP Error Code:" + WebResp.StatusCode.ToString());
            }

            if (xDoc == null) throw new Exception("El XmlDocument obtenido de DineroMail es null");

            return xDoc;
        }
        catch (Exception ex)
        {
            string datosStr = "";
            foreach (DictionaryEntry entry in ex.Data)
            {
                datosStr = entry.Key.ToString() + ": " + entry.Value.ToString() + "\r\n";
            }
            this.WriteToEventLog("Metodo makeHTTPrequest(string url, string parametersStr)\r\nParametros: url=" + url + " parametersStr= " + parametersStr + "\r\nDatos Excepcion (Cantidad "+ex.Data.Count.ToString()+"):\r\n"+ datosStr +"Descripcion:\r\n" + ex.Message + "\r\nSource:\r\n" + ex.Source + "\r\nStackTrace:\r\n" + ex.StackTrace + "\r\n");
            throw ex;
        }
    }

This works fine on my develpment environment (my PC), but when I move to the Production Server environment (Windows 2008 with IIS) I get an HTTP 400 error when I make the WebRequest. To make it even more difficult to debug this happens intermintently. This means that it works OK for a while but after some time it stops working and throws the HTTP 400 error. Another extra information: From another Web Method of the Web Service I call another Web Service which some times throws the same error intermitently too. Another extra information: I access Internet through the company Proxy Does anybody know what can be wrong? I been trying to work this out for a few days with no luck, so any ideas are welcome :-)

Thanks!

A similar problem is reported here: .Net HttpWebRequest.GetResponse() raises exception when http status code 400 (bad request) is returned .

Also I noticed that you are not disposing the Response object. Could the previous response being still alive in the finalizing queue of the garbage collector be causing a problem?

using( HttpWebResponse WebResp = (HttpWebResponse)WebReq.GetResponse() )
{
  if (WebResp.StatusCode == HttpStatusCode.OK)
            {
                sAnswer = WebResp.GetResponseStream();
                xDoc.Load(sAnswer);
            }
            else
            {
                throw new Exception("No se obtuvo una respuesta satisfactoria del servidor\r\nHTTP Error Code:" + WebResp.StatusCode.ToString());
            }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM