0

语境:

我正在改进我的 .dll 以执行 WebRequests(Get 和 Post),添加一个新功能,即:响应后自动编码检测

它将如何工作:

  1. 库的用户为请求配置它的默认参数,包括编码
  2. 库执行对某个 url 的请求
  3. 库检查页面的编码是否与预先配置的相同(通过检查元标记的值)
  4. 如果编码不同,我使用正确的编码(在页面上找到的那个)重新编码响应

代码片段:

           // Executes web request and wait for response
            using (HttpWebResponse resp = (HttpWebResponse) m_HttpWebRequest.GetResponse())
            {
                using (var stream = resp.GetResponseStream ())
                {
                    using (var reader = new StreamReader (stream))
                    {
                        // Reading Stream to the end
                        response = reader.ReadToEnd ();

                        // Identifying the encode used on the page
                        // I will not paste method here, but it works
                        m_PageEncoding = IdentifyEncoding (response);                            
                    }

                    // Checking if the page encode is not the same as the preconfigured one
                    if (m_PageEncoding != System.Text.Encoding.GetEncoding (m_encoding))
                    {
                        using (var encodedReader = new StreamReader (stream, m_PageEncoding))
                        {
                            response = encodedReader.ReadToEnd();                                
                        }
                    }
                }
            }

问题:

一旦我创建了另一个EncodedReader带有 Encoding 参数的 Reader,就会引发异常:Stream was not readable.

如果,我使用块将读取器嵌套在 responseStream 中,则第二次读取后的响应值始终为“空”

using (var stream = resp.GetResponseStream ())
                {
                    using (var reader = new StreamReader (stream))
                    {
                        // Reading Stream to the end
                        response = reader.ReadToEnd ();

                        // Identifying the encode used on the page
                        m_PageEncoding = IdentifyEncoding (response);

                        // Checking if the page encode is not the one i've used as argument
                        if (m_PageEncoding != System.Text.Encoding.GetEncoding(m_encoding))
                        {
                            using (var encodedReader = new StreamReader(stream, m_PageEncoding))
                            {
                                response = encodedReader.ReadToEnd();
                            }
                        }                         
                    }
                }

问题:

如何在同一个 WebResponse 上执行两次 ReadToEnd 方法,而不执行两次请求,这很糟糕。

4

0 回答 0