开发者

The correct way to retrieve data from a HttpWebRespose Stream then add text

开发者 https://www.devze.com 2023-01-09 19:08 出处:网络
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 frame开发者_StackOverflow中文版work of what I am trying to do. Is this

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 frame开发者_StackOverflow中文版work 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());


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:

WebClient web_client = new WebClient();
byte[] result = web_client.DownloadData("http://blah...");
string html = System.Text.Encoding.Default.GetString(result);
html.IndexOf("<body>") ...

Little bit less code like that as well.


At some point, you may want to call responce.Close() and reader.Close()

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号