HttpWebRequest GetResponse.如何等待该响应? [英] HttpWebRequest GetResponse. How to wait for that response?
问题描述
我正在使用HttpWebRequest
发送一些SMS.但是有时消息似乎发送两次,三遍甚至更多遍,对所有过程进行检查似乎都可以.
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.
我认为唯一的一件事是HttpWebRequest正在异步工作.
The only thing i think is HttpWebRequest is working asynchronus.
这是我的代码
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();
返回正确的代码.
我的问题是..有一种方法可以停止该过程,或强制代码等待直到(httpWebRequest send the message and get the response)
或(timeout succeed)
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)
推荐答案
HttpWebRequest.BeginGetResponse()
,那么您将需要另一种机制来等待异步接收响应.
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.
如果要发送多条SMS消息,则可能是由于在收到StrSMSGatewayRespuesta
时未收到正确的响应代码而引起的.如果您输入的代码错误,但实际上已发送了该消息,则由于您将其标记为未发送,因此该消息很可能会再次发送.
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.
这篇关于HttpWebRequest GetResponse.如何等待该响应?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!