从 HttpWebRespose Stream 检索数据然后添加文本的正确方法
我正在尝试检索网页,在页面顶部添加一些文本,然后我将发送该字符串。这是我正在尝试做的示例框架。这是正确的方法还是我在某个地方做了很大的禁忌?
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.example.com");
var responce = (HttpWebResponse)request.GetResponse();
var responseStream = responce.GetResponseStream();
StreamReader reader = new StreamReader(responseStream);
string responseString = reader.ReadToEnd();
StringBuilder sb = new StringBuilder(responseString);
var index = sb.ToString().IndexOf("<body>", StringComparison.InvariantCultureIgnoreCase)+"<body>".Length;
sb.Insert(index, "A lot of text will go here.");
Console.WriteLine(sb.ToString());
I am trying to retrieve a web page, add some text at the top of the page then I will be sending off the string. Here is a example framework of what I am trying to do. Is this the correct method or am I doing a big no-no somewhere?
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.example.com");
var responce = (HttpWebResponse)request.GetResponse();
var responseStream = responce.GetResponseStream();
StreamReader reader = new StreamReader(responseStream);
string responseString = reader.ReadToEnd();
StringBuilder sb = new StringBuilder(responseString);
var index = sb.ToString().IndexOf("<body>", StringComparison.InvariantCultureIgnoreCase)+"<body>".Length;
sb.Insert(index, "A lot of text will go here.");
Console.WriteLine(sb.ToString());
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在某些时候,您可能想要调用 responce.Close() 和 reader.Close()
At some point, you may want to call responce.Close() and reader.Close()
您需要使用 HttpWebRequest/Response 有什么特殊原因吗?您也可以使用这样的 WebClient 类来实现相同的结果:
也可以少一点这样的代码。
Is there any particular reason you need to use HttpWebRequest/Response? You could alternatively use the WebClient class like this to achieve the same result:
Little bit less code like that as well.