【发布时间】:2019-10-04 13:52:42
【问题描述】:
你好溢出社区,
我有一个小问题。我写了一个类,它只是一个简单的获取请求,其中包含 url、引用者和 cookie 的参数,然后它返回 pagesrc,这是我的获取字符串函数的消息,它有一个消息、开始和停止参数。
这是类:
class HttpMethods
{
public static string Fetch(string url, string referer, ref CookieContainer cookies)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "GET";
request.CookieContainer = cookies;
request.UserAgent = "" ;
request.Referer = referer;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
cookies.Add(response.Cookies);
string pageSrc;
using (StreamReader sr = new StreamReader(response.GetResponseStream()))
{
pageSrc = sr.ReadToEnd();
}
return pageSrc;
}
}
这是我的主要功能:
static void Main(string[] args)
{
CookieContainer myCookies = new CookieContainer();
string myStr = HttpMethods.Fetch("localhost", "localhost", ref myCookies);
void fetchStr (string message , string start, string stop)
{
int startIndex = message.IndexOf(start) + start.Length;
int stopIndex = message.IndexOf(stop);
Console.Write( message.Substring(startIndex, stopIndex - startIndex) );
}
fetchStr(myStr, "I am a String ", " to fetch");
Console.ReadKey();
}
}
当我只获取纯文本时一切正常,但是当我想获取一个元素时,它返回给我长度不能小于 0,这是未找到某些字符串时的响应。
这真的很奇怪,这里有一个例子:
//Original Sentence : I am a string please fetch me dude.
fetchStr(myStr, "I am a ", " fetch me dude");
这将返回:请字符串
但是当我尝试获取这部分时:
//Original Sentence : name="_playerToken" value="a8276964-fdac-4d63-ae25-5752f157a21b" />
fetchStr(myStr, "name=\"_playerToken\" value=\"", "\"/>");
这将返回长度不能小于0。
这是我的 Visual Studio 输出的屏幕截图:
有人知道问题出在哪里吗?
【问题讨论】:
-
请注意:
request.CookieContainer = cookies;足以处理 cookie;不需要cookies.Add(response.Cookies);。
标签: c# substring httpwebrequest indexof