HttpWebRequest每次都不起作用

时间:2013-03-27 11:48:25

标签: c# httpwebrequest

我正在对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;
}

我该如何解决这个问题?

2 个答案:

答案 0 :(得分:0)

如果你想重试,如果返回的结果最终为null ..为什么不做这样的事情:

private void RunWebrequest()
{
     if (HttpWebRequest() == null)
     {
          RunWebrequest();
     }
     else
     {
          //continue
     }
}

答案 1 :(得分:0)

我在此服务器上遇到了同样的问题,而不是放置您的用户名和用户名。根据旅行记录文件使用“凭据”代替网址中的密码: -

string travelineUrl = "http://nextbus.mxdata.co.uk/nextbuses/1.0/1";        
var travelineRequest = (HttpWebRequest)WebRequest.Create(travelineUrl);
travelineRequest.Credentials = new NetworkCredential("yourusername", "yourpassword");