HttpWebRequest GetResponse. How to wait for that r

2019-07-24 06:11发布

问题:

I'm sending some SMS using HttpWebRequest. But some times the messages appear to send double, three times and more reviewing all the proccess appear to be ok.

The only thing i think is HttpWebRequest is working asynchronus.

here is my code,

    public bool sendSmsGateway(string tcDestino, string tcMensaje, string tcTitulo = "")
    {
        bool lReturn = false;
        string contenido = HttpUtility.UrlEncode(tcMensaje);
        string lcTitulo = "SMS Sender";
        if (!String.IsNullOrEmpty(tcTitulo))
        {
            lcTitulo = tcTitulo;
        }
        lcTitulo = HttpUtility.UrlEncode(lcTitulo);
        string fechaEnvio = DateTime.Now.ToString("s"); 
        string url = string.Format(StrSMSGatewayURL, StrSMSGatewayUsuario, StrSMSGatewayPassword, tcDestino, contenido, lcTitulo, fechaEnvio);
        HttpWebRequest enviar = (HttpWebRequest)WebRequest.Create(url);
        string respuesta = new StreamReader(enviar.GetResponse().GetResponseStream()).ReadToEnd();

        StrSMSGatewayRespuesta = respuesta.Trim();
        if (StrSMSGatewayRespuesta  == StrSMSGatewayRespuestaOk.Trim())
        {
            lReturn = true;
        }
        return lReturn;
    }

this code runs in loop routine that send the message and mark it as sent when:

string respuesta = new StreamReader(enviar.GetResponse().GetResponseStream()).ReadToEnd();

return the propper code.

My question is.. there is a way to stop the proccess, or force the code to wait until the (httpWebRequest send the message and get the response) or (timeout succeed)

回答1:

HttpWebRequest.GetResponse() is a synchronous call, so you don't need to have a different mechanism for blocking the current thread. If you were using the asynchronous method HttpWebRequest.BeginGetResponse(), then you would need to have another mechanism to wait for the response to be asynchronously received.

If you're sending multiple SMS messages, then this is probably caused by not receiving the correct response code when you get StrSMSGatewayRespuesta. If you get the wrong code but the message was actually sent, then the message is likely to be sent again since you're marking it as not sent.