HttpWebRequest并不是每次都工作
本文关键字:工作 并不是 HttpWebRequest | 更新日期: 2023-09-27 18:06:01
我正在做WebRequest
到Uri
,但问题是我每次都没有得到响应。有时我需要重做。我希望我的程序检查它是否没有响应,如果是,程序将自动召回WebRequest
的方法,直到我得到响应。
while(response == null)
{
try it again
}
这是我的功能。大写的注释是对我的问题的解释
private string HttpWebRequest()
{
string xml = @"<?xml version='1.0' encoding='UTF-8' standalone='yes'?>
<Siri version='1.0' xmlns='http://www.siri.org.uk/'>
<ServiceRequest>
<RequestTimestamp>2011-10-24T15:09:12Z</RequestTimestamp>
<RequestorRef><USERNAME></RequestorRef>
<StopMonitoringRequest version='1.0'>
<RequestTimestamp>2011-10-24T15:09:12Z</RequestTimestamp>
<MessageIdentifier>12345</MessageIdentifier>
<MonitoringRef>020035811</MonitoringRef>
</StopMonitoringRequest>
</ServiceRequest>
</Siri>";
string responseFromServer = null;
WebRequest request = WebRequest
.Create("http://<USERNAME>:<PASSWORD>@nextbus.mxdata.co.uk/nextbuses/1.0/1");
request.Method = "POST";
string postData = xml;
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = byteArray.Length;
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
////////IF I GET NO RESPONSE EVERYTHING AFTER THE NEXT LINE WILL BE IGNORED
WebResponse response = request.GetResponse();
///////////THIS MESSAGEBOX WILL BE IGNORED
MessageBox.Show(((HttpWebResponse)response).StatusDescription+" Completed");
dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
responseFromServer = reader.ReadToEnd();
reader.Close();
dataStream.Close();
response.Close();
return responseFromServer;
}
如何解决这个问题?
如果您想重试,如果返回的结果最终为null..为什么不这样做呢:
private void RunWebrequest()
{
if (HttpWebRequest() == null)
{
RunWebrequest();
}
else
{
//continue
}
}
我在这个服务器上有同样的401问题,而不是放置您的用户名&根据traveline文档,使用"Credentials"代替url中的密码:-
string travelineUrl = "http://nextbus.mxdata.co.uk/nextbuses/1.0/1";
var travelineRequest = (HttpWebRequest)WebRequest.Create(travelineUrl);
travelineRequest.Credentials = new NetworkCredential("yourusername", "yourpassword");