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()
精彩评论