HttpWebRequest を使用して、POST メソッドで Web ページのソース コードを取得しています。このページには、さまざまなパラメーターを使用して複数回アクセスする必要があります。
短期間に 2 回目の応答を取得すると、常に同じ応答オブジェクトが返されます。デバッグ後、2 回目の呼び出しが約 30 秒後であれば、リクエストは正しい応答オブジェクト (ソース コード) を取得できます。
public HtmlAgilityPack.HtmlDocument getHtmlData(string url, string cname)
{
HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
try
{
HttpRequestCachePolicy policy = new HttpRequestCachePolicy(HttpRequestCacheLevel.Default);
HttpWebRequest.DefaultCachePolicy = policy;
HttpRequestCachePolicy noCachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.NoCacheNoStore);
HttpWebRequest req = WebRequest.Create(url) as HttpWebRequest;
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
req.KeepAlive = false;
req.Headers[HttpRequestHeader.CacheControl] = "no-cache";
req.Headers[HttpRequestHeader.Pragma] = "no-cache";
req.IfModifiedSince = DateTime.Now;
req.CachePolicy = noCachePolicy;
//add post data
string postData = "cname=" + cname;
byte[] byteArray = Encoding.GetEncoding("shift-jis").GetBytes(postData);
req.ContentLength = byteArray.Length;
using (Stream stream = req.GetRequestStream())
{
stream.Write(byteArray, 0, byteArray.Length);
}
// get response
string data = "";
HttpWebResponse response = req.GetResponse() as HttpWebResponse;
using (var stream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(stream, Encoding.GetEncoding("shift-jis"));
data = reader.ReadToEnd();
reader.Close();
}
response.Close();
doc.LoadHtml(data);
//System.Threading.Thread.Sleep(30000);
}
catch(Exception ex)
{
Log.log.Debug(ex.ToString());
}
return doc;
}
関数呼び出しブロック:
getHtmlData(@"http://www.jra.go.jp/JRADB/accessS.html", "pw01sli00/AF");
getHtmlData(@"http://www.jra.go.jp/JRADB/accessS.html", "pw01skl00999999/B3");
getHtmlData(@"http://www.jra.go.jp/JRADB/accessS.html", "pw01skl00201604/E3");
私は一日中その問題に固執しました。誰かが私に手がかりを与えてくれることを願っています。
どうもありがとう!