所以,这是我制作的一个场景,我正在创建自己的网络浏览器,我想确保我向网络服务器发送正确的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 .....
提前致谢。
[UPDATE]
很明显,我已经在我的WebRequest实例中提供了所有已发布的请求(POST)文本。
有没有方便地从中获取整个纯文本,而不是使用ContentType
或Headers
等分离的get属性?
(因为我懒得将我指定的所有标题组合到整个完整的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.
}
答案 0 :(得分:0)
您的问题非常模糊,但是,我相信您正在寻找的内容包括Webrequest中的标题。 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 ();
}
答案 1 :(得分:0)
如果你说你不想通过请求属性获得一些标题,例如" request.ContentType"和其他通过标头集合,然后你可以使用标头集合,因为它已经包含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;
}
}
}