Does this HttpWebRequest/HttpWebResponse/StreamReader code even make sense?

拈花ヽ惹草 提交于 2019-12-11 19:50:03

问题


Rather than add on to my question here, I'm adding a new one as, once I looked at my code with my X-Ray vision goggles attached, I don't grok it.

I don't even remember where I got this code, but it's an adaptation of an example I found somewhere. Yet it doesn't seem that the data is even being sent to the server. To be specific, this code:

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;
        }
    }
}

...seems to be doing this:

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()
  • but what does "request" contain? The contents (of the StreamReader => StringBuilder => Array of Bytes => Stream) are never assigned to it! It seems as if the Stream exists for the sole purpose of writing lines of code, heating up the processor, and slowing down the operation!

Is this code nonsensical, or am I just not grokking it?


回答1:


GetRequestStream() returns a stream that forwards writes through the HttpWebRequest to the network.
Your code is unnecessarily long, but correct.

However, response.ToString() is wrong; you want to read response.GetResponseStream() with a StreamReader.



来源:https://stackoverflow.com/questions/22360763/does-this-httpwebrequest-httpwebresponse-streamreader-code-even-make-sense

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!