Имеет ли вообще смысл этот код 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 существует только для того, чтобы писать строки кода, нагревать процессор и замедлять работу!

Является ли этот код бессмысленным, или я просто не понимаю его?


person B. Clay Shannon    schedule 12.03.2014    source источник
comment
Вместо этого используйте HttpClient; это намного проще.   -  person SLaks    schedule 12.03.2014
comment
Вы можете заменить десять строк кода на File.ReadAllBytes()   -  person SLaks    schedule 12.03.2014
comment
Я не думаю, что HttpClient доступен в Compact Framework.   -  person B. Clay Shannon    schedule 12.03.2014
comment
File.ReadAllBytes(), похоже, также недоступен в Compact Framework. CF ненавидит легкий путь.   -  person B. Clay Shannon    schedule 12.03.2014


Ответы (1)


GetRequestStream() возвращает поток, который пересылает записи через HttpWebRequest в сеть.
Ваш код излишне длинный, но правильный.

Однако response.ToString() неверно; вы хотите прочитать response.GetResponseStream() с StreamReader.

person SLaks    schedule 12.03.2014
comment
Вы имеете в виду просто заменить return response.ToString(); с возвратом ответа.GetResponseStream().ToString();? - person B. Clay Shannon; 12.03.2014
comment
Я думаю, что нет, потому что это дает мне NotSupportedException, а значение val по-прежнему равно нулю. - person B. Clay Shannon; 12.03.2014
comment
Нет; Я имею в виду создать StreamReader и вызвать ReadToEnd() - person SLaks; 12.03.2014
comment
У меня уже есть StreamReader; вы имеете в виду другой StreamReader (вместо Stream)? - person B. Clay Shannon; 12.03.2014
comment
Я внес изменения на основе этого предложения, которые появляются в обновлении 4 здесь: stackoverflow.com/questions/22358231/ - person B. Clay Shannon; 13.03.2014