当搜索字符串时,HttpWebResponse返回5个数字
本文关键字:返回 5个 数字 HttpWebResponse 搜索 字符串 | 更新日期: 2023-09-27 18:13:38
using System;
using System.IO;
using System.Net;
using System.Text;
/// <summary>
/// Fetches a Web Page
/// </summary>
class WebFetch
{
static void Main(string[] args)
{
// used to build entire input
StringBuilder sb = new StringBuilder();
// used on each read operation
byte[] buf = new byte[8192];
// prepare the web page we will be asking for
HttpWebRequest request = (HttpWebRequest)
WebRequest.Create("http://www.nbcwashington.com/weather/school-closings/");
// execute the request
HttpWebResponse response = (HttpWebResponse)
request.GetResponse();
// we will read data via the response stream
Stream resStream = response.GetResponseStream();
string tempString = null;
int count = 0;
do
{
// fill the buffer with data
count = resStream.Read(buf, 0, buf.Length);
// make sure we read some data
if (count != 0)
{
// translate from bytes to ASCII text
tempString = Encoding.ASCII.GetString(buf, 0, count);
// continue building the string
sb.Append(tempString);
}
}
while (count > 0); // any more data to read?
// print out page source
Console.WriteLine(sb.ToString());
Console.Clear ();
string output = sb.ToString();
string searchForThis = "Open";
int firstCharacter = output.IndexOf(searchForThis);
Console.WriteLine(output.IndexOf(searchForThis));
Console.ReadLine();
}
}
我正在写一些代码,将去一个网站,抓取一些文本,并将其粘贴到控制台视图HttpWebResponse,但是当我使用IndexOf()它返回5个数字,如"22452"。是的,我知道这段代码可能相当潦草,但我才刚刚开始。为什么会这样?
根据MSDN IndexOf方法:
报告第一次出现的从零开始的索引
返回值类型:System。Int32
如果找到该字符串,则value的从零开始的索引位置,或者-1如果不是。如果value是字符串。空,返回值为0。
所以这个22452
是Open
在输出字符串变量中第一次出现的索引位置。
另外,如果你可以使用StreamReader,为什么你要使用Stream
?Stream是一个抽象类,它的有用方法没有特定的实现。
你可以这样写:
using System;
using System.IO;
using System.Net;
using System.Text;
/// <summary>
/// Fetches a Web Page
/// </summary>
class WebFetch
{
static void Main(string[] args)
{
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("http://www.nbcwashington.com/weather/school-closings/");
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream rawStream = response.GetResponseStream();
string resOutput = String.Empty();
using (StreamReader reader = new StreamReader(rawStream))
{
resOutput = reader.ReadToEnd();
}
Console.WriteLine(resOutput);
Console.Clear();
string searchForThis = "Open";
int firstCharacter = resOutput.IndexOf(searchForThis);
Console.WriteLine(resOutput.IndexOf(searchForThis))
Console.ReadLine();
response.Close();
}
}