如何从 WebRequest 获取流中的文本?

How to get text in stream from WebRequest?

所以,这是我编造的一个场景,我正在制作自己的网络浏览器,我想确保向网络服务器发送正确的 POST 文本。

为了实现这一点,我需要在调用 GetResponseStream().

之前获取 WebRequest 为我创建的 POST 文本

我试图通读来自 WebRequest.GetRequestStream() 的流,但我认为这不是一种方法。

我不希望 Web 服务器响应 HTML 纯文本。 我需要获取的 POST 文本必须如下所示:

POST http://www.some_web_server.com/default.aspx HTTP/1.1 
Cache-Control : max-age=0 Connection : keep-alive .....

提前致谢。

[更新]

很明显,我已经在我的 WebRequest 实例中编写了所有 request(POST) 文本。

有什么方法可以方便地从中获取整个纯文本,而不是使用单独的获取属性,例如 ContentTypeHeaders

(因为我懒得 'assemble' 我指定的所有 headers 到整个完整的 POST 文本中,Web 服务器最终会看到。)

// This might be a very poor code to approach.

public void Show_Full_POST_Text(WebRequest req)
{
    // For example.
    String strRawText = req.GetRequestLiteral();

    // Your POST text looks like this!
    ShowToUser(strRawText);
}

public void Foo()
{
    // ...

    Show_Full_POST_Text(req);
    var ResponseStream = req.GetResponseStream();

    // Continue.
}

你的问题很含糊,但是,我相信你正在寻找的是在 Webrequest 中包含 headers。 The MSDN has a good example。见下文:

public static void Main (string[] args)
{
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create (args[0]);

    // Set some reasonable limits on resources used by this request
    request.MaximumAutomaticRedirections = 4;
    request.MaximumResponseHeadersLength = 4; //This sets the max headers coming back to your response.
    // Set credentials to use for this request.
    request.Credentials = CredentialCache.DefaultCredentials;
    HttpWebResponse response = (HttpWebResponse)request.GetResponse ();

    Console.WriteLine ("Content length is {0}", response.ContentLength);
    Console.WriteLine ("Content type is {0}", response.ContentType);

    // Get the stream associated with the response.
    Stream receiveStream = response.GetResponseStream ();

    // Pipes the stream to a higher level stream reader with the required encoding format. 
    StreamReader readStream = new StreamReader (receiveStream, Encoding.UTF8);

    Console.WriteLine ("Response stream received.");
    Console.WriteLine (readStream.ReadToEnd ());
    response.Close ();
    readStream.Close ();
}

如果您说您不想通过请求属性(例如 "request.ContentType" 和其他通过 header collection 获取一些 header,那么您可以只使用 header collection 因为它已经包含了 ContentType 的密钥。

using System;
using System.Collections.Generic;
using System.Net;

namespace Demo
{
    class Program
    {
        static void Main(string[] args)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.example.com");
            request.Method = "POST";
            request.ContentType = "image/png";

            Console.WriteLine(GetRequestAsString(request));
            Console.ReadKey();
        }

        public static string GetRequestAsString(HttpWebRequest request)
        {
            string str = request.Method + " " + request.RequestUri + " HTTP/" + request.ProtocolVersion + Environment.NewLine;
            string[] headerKeys = request.Headers.AllKeys;

            foreach (string key in headerKeys)
            {
                str += key + ":" + request.Headers[key];
            }

            return str;
        }
    }
}