我正在尝试解决一个我最常见的问题(70%)(30%是成功的)。
我尝试使用以下代码执行webrequest(POST):
private string HttpWebRequest(string busStopCode)
{
//XML input
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>"+busStopCode+"</MonitoringRef></StopMonitoringRequest></ServiceRequest></Siri>";
string responseFromServer = null;
// Create a request using a URL that can receive a post.
WebRequest request = WebRequest.Create("http://<username>:<username>@nextbus.mxdata.co.uk/nextbuses/1.0/1");
// Set the Method property of the request to POST.
request.Method = "POST";
request.Credentials = CredentialCache.DefaultNetworkCredentials;
// Create POST data and convert it to a byte array.
string postData = xml;
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
// Set the ContentType property of the WebRequest.
request.ContentType = "application/x-www-form-urlencoded";
// Set the ContentLength property of the WebRequest.
request.ContentLength = byteArray.Length;
// Get the request stream.
Stream dataStream = request.GetRequestStream();
// Write the data to the request stream.
dataStream.Write(byteArray, 0, byteArray.Length);
// Close the Stream object.
dataStream.Close();
// Get the response.
WebResponse response = null;
while (response == null)
{
try
{
response = request.GetResponse();
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
}
}
// Display the status.
MessageBox.Show(((HttpWebResponse)response).StatusDescription + " Completed");
// Get the stream containing content returned by the server.
dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.
responseFromServer = reader.ReadToEnd();
// Clean up the streams.
reader.Close();
dataStream.Close();
response.Close();
return responseFromServer;
}
当我调用此函数时,我主要得到一个异常的消息框:
"System.Net.WebException: The remote Server returned an error(401) not authorized with System.Net.Http.Webrequest.GetResponse() with WindowsFormApplication1.Form1.HttpWebRequest(string BusstopCode) in <my pathfile>...."
我做错了什么?
我已经尝试过以前线程的几个解决方案,但没有成功......
谢谢!