WebRequest

Webページを取得する場合など、HTTPリクエストを作成するには、WebRequestを使う・・・。

WebRequest クラス (System.Net)

"http://bgstation0.com"のトップページのHTMLを取得する・・・。

f:id:BG1:20170310181329p:plain

今回は空のプロジェクトで・・・。
(コンソールでもいいんだけど・・・。)

MainClass.csを追加したら、

f:id:BG1:20170310181440p:plain

参照が足りない(というか空だから無い・・・。)ので追加する・・・。

f:id:BG1:20170310181525p:plain

Systemを追加・・・。

でMainClass.csは、

WebRequestはSystem.Net名前空間、Stream系はSystem.IO名前空間なので追加・・・。

response、stream、srはnullをセットしておく・・・。
tryの中で、まずはWebRequest.Createに"http://bgstation0.com"を指定してrequest作成・・・。
今度はrequest.GetResponseでresponseを取得・・・。
responseからresponse.GetResponseStreamでstreamを取得・・・。
しかし、これでは文字列として読み込めないので、StreamReaderのコンストラクタに渡してsrを取得・・・。
sr.ReadToEndでようやく文字列としてstrに格納・・・。
あとは、Console.Writeでstrを出力・・・。

例外が起きたら、catchブロックでex.ToString()で例外内容を出力・・・。

finallyでリソース解放・・・。
reqeustはCloseが無いみたいなので、sr、stream、responseをCloseで閉じる・・・。
(なのでMainブロックに宣言がある・・・。)

<html>
  <head>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
    <title id="title_index">B.G-STATION</title>
  </head>
  <body id="body_index" bgcolor="#ffffff" text="#7700cc" link="0000ff" alink="ff
0000" vlink="ff00ff">
    <div id="div_titleimage" align="center">
      <img src="http://www.geocities.co.jp/bg_sta/resource/image/title.png" widt
h="460px" height="140px" />
    </div>
    <div id="div_mainmenu" align="center">
      <div id="div_item_sample">
        <a href="sample/index.html">Sample</a>
      </div>
    </div>
  </body>
</html>
続行するには何かキーを押してください . . .

こんな感じで、WebページのHTMLが取得できる・・・。

Sample/dotnet/WebRequest/WebRequest/src/WebRequest_ at master · bg1bgst333/Sample · GitHub