我沒有加入到我的問題here中,而是添加了一個新的,因爲一旦我連接了我的X-Ray視覺護目鏡查看我的代碼,我就不理睬它。這個HttpWebRequest/HttpWebResponse/StreamReader代碼是否有意義?
我什至不記得我在哪裏得到這段代碼,但它是我在某處找到的一個例子的改編。然而,數據似乎並沒有被髮送到服務器。具體而言,此代碼:
public static string SendXMLFile(string xmlFilepath, string uri)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.KeepAlive = false;
request.ProtocolVersion = HttpVersion.Version10;
request.Method = "POST";
StringBuilder sb = new StringBuilder();
using (StreamReader sr = new StreamReader(xmlFilepath))
{
String line;
while ((line = sr.ReadLine()) != null)
{
// test to see if it's finding any lines
//MessageBox.Show(line); <= works fine
sb.AppendLine(line);
}
byte[] postBytes = Encoding.UTF8.GetBytes(sb.ToString());
request.ContentLength = postBytes.Length;
// Did the sb get into the byte array?
//MessageBox.Show(request.ContentLength.ToString()); <= shows "112" (seems right)
request.KeepAlive = false;
request.ContentType = "application/xml";
try
{
Stream requestStream = request.GetRequestStream();
// now test this: MessageBox.Show() below causing exception? See https://stackoverflow.com/questions/22358231/why-is-the-httpwebrequest-body-val-null-after-crossing-the-rubicon
//MessageBox.Show(string.Format("requestStream length is {0}", requestStream.Length.ToString()));
requestStream.Write(postBytes, 0, postBytes.Length);
MessageBox.Show(string.Format("requestStream length is {0}", requestStream.Length.ToString()));
requestStream.Close();
using (var response = (HttpWebResponse)request.GetResponse())
{
return response.ToString();
}
}
catch (Exception ex)
{
MessageBox.Show("SendXMLFile exception " + ex.Message);
request.Abort();
return string.Empty;
}
}
}
...似乎是這樣:
0) Reads the contents of the file at xmlFilepath and puts it into a StreamReader ("sr")
1) A StringBuilder ("sb") is populated with the contents of the StreamReader
2) The contents of the StringBuilder are put into an array of Bytes ("postBytes")
- then here comes the weird part (or so it seems to me, after analyzing the code more closely):
3) The contents of the array of bytes are written to a Stream ("requestStream")
4) The Stream is closed (???)
5) The HttpWebRequest ("request") attempts to return a HttpWebResponse by calling GetResponse()
- 但到底是什麼 「要求」 包含哪些內容? (StreamReader => StringBuilder => Array of Bytes => Stream)的內容永遠不會被分配給它!看起來好像Stream的存在只是爲了編寫代碼行,加熱處理器,並放慢操作!
這段代碼無意義了,還是我只是沒有在意它呢?
改爲使用'HttpClient';這很容易。 – SLaks
你可以用'File.ReadAllBytes()'代替十行代碼' – SLaks
我不認爲HttpClient在Compact Framework中可用。 –