.NET TIPS
HTTPステータス・コードを取得しWebページの存在を確認するには?[C#、VB]
デジタルアドバンテージ 遠藤 孝信
2008/12/11
任意のURLにより指定されたWebページが存在するかどうか(実際にアクセスできるかどうか)は、Webサーバにアクセスし、その応答時に返されるHTTPステータス・コードを調べることによりチェック可能だ。
HTTPステータス・コードとは、HTTP通信時におけるWebサーバからの応答の状態を表すためのもので、RFC 2616(Hypertext Transfer Protocol -- HTTP/1.1) で定義されており、.NETのクラス・ライブラリではコードの一覧がSystem.Net名前空間のHttpStatusCode列挙体で定義されている。
RFC 2616に掲載されているHTTPステータス・コードと、HttpStatusCode列挙体の値の一覧を次の表に示す。
コード値
RFC 2616で定義された意味
HttpStatuCode列挙体の値
100
Continue
Continue
101
Switching Protocols
SwitchingProtocols
200
OK
OK
201
Created
Created
202
Accepted
Accepted
203
Non-Authoritative Information
NonAuthoritativeInformation
204
No Content
NoContent
205
Reset Content
ResetContent
206
Partial Content
PartialContent
300
Multiple Choices
MultipleChoices
300
Ambiguous
301
Moved Permanently
Moved
301
MovedPermanently
302
Found
Found
302
Found
Redirect
303
See Other
RedirectMethod
303
SeeOther
304
Not Modified
NotModified
305
Use Proxy
UseProxy
306
−
Unused
307
Temporary Redirect
RedirectKeepVerb
307
TemporaryRedirect
400
Bad Request
BadRequest
401
Unauthorized
Unauthorized
402
Payment Required
PaymentRequired
403
Forbidden
Forbidden
404
Not Found
NotFound
405
Method Not Allowed
MethodNotAllowed
406
Not Acceptable
NotAcceptable
407
Proxy Authentication Required
ProxyAuthenticationRequired
408
Request Time-out
RequestTimeout
409
Conflict
Conflict
410
Gone
Gone
411
Length Required
LengthRequired
412
Precondition Failed
PreconditionFailed
413
Request Entity Too Large
RequestEntityTooLarge
414
Request-URI Too Large
RequestUriTooLong
415
Unsupported Media Type
UnsupportedMediaType
416
Requested range not satisfiable
RequestedRangeNotSatisfiable
417
Expectation Failed
ExpectationFailed
500
Internal Server Error
InternalServerError
501
Not Implemented
NotImplemented
502
Bad Gateway
BadGateway
503
Service Unavailable
ServiceUnavailable
504
Gateway Time-out
GatewayTimeout
505
HTTP Version not supported
HttpVersionNotSupported
HTTPステータス・コードとHttpStatusCode列挙体の値の一覧
HttpStatusCode列挙体では、1つのHTTPステータス・コードに対して複数の値が割り当てられている場合がある。
HTTPステータス・コードを取得するには、まずWebページにアクセスする。これに関しては、リクエストを示すHttpWebRequestクラスと、レスポンス(応答)を示すHttpWebResponseクラス(ともにSystem.Net名前空間)を使用する。これらのクラスの利用方法については「TIPS:WebRequest/WebResponseクラスでWebページを取得するには? 」を参照してほしい。
Webサーバから応答があった場合には、WebサーバからのレスポンスであるHttpWebResponseオブジェクトのStatusCodeプロパティにHttpStatusCode列挙体の値がセットされる。
ただし、例えばページが存在しない場合には、HttpWebResponseオブジェクトの取得時に例外が発生する。それでもWebサーバが応答している場合には、例外オブジェクトであるWebExceptionオブジェクト(System.Net名前空間)のResponseプロパティからHttpWebResponseオブジェクトが取得できるため、この場合にもHTTPステータス・コードを得ることができる。
ここで注意しなければならないのは、Webサーバが応答しない場合(例えばサーバのアドレスが間違っている、ネットワークが利用できない、などの場合)にも同様に例外が発生するという点だ。この場合にはレスポンスを得られないため、HTTPステータス・コードも取得不可能だ。
以上の手順を実装すると、次のリストのGetStatusCodeメソッドのようになる。なお、このメソッドでは、レスポンスを得られない場合は例外をそのまま再スローしている。
// pagecheck.cs
using System;
using System.Net;
class PageCheck {
// urlにアクセスしてステータス・コードを返す
static public HttpStatusCode GetStatusCode(string url) {
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse res = null;
HttpStatusCode statusCode;
try {
res = (HttpWebResponse)req.GetResponse();
statusCode = res.StatusCode;
} catch (WebException ex) {
res = (HttpWebResponse)ex.Response;
if (res != null) {
statusCode = res.StatusCode;
} else {
throw; // サーバ接続不可などの場合は再スロー
}
} finally {
if (res != null) {
res.Close();
}
}
return statusCode;
}
// ページが存在するかチェックするサンプル
static void Main(string[] args) {
string url = "http://www.atmarkit.co.jp/nosuchpage.html";
WebRequest.DefaultWebProxy = null; // プロキシ未使用を明示
HttpStatusCode statusCode = GetStatusCode(url);
int code = (int)statusCode; // 列挙体の値を数値に変換
if (code >= 400) { // 4xx、5xxはアクセス失敗とする
Console.WriteLine("ページは存在しないようです:" + code);
} else {
Console.WriteLine("ページは存在します:" + code);
}
// 出力:ページは存在しないようです:404
}
}
// コンパイル方法:csc pagecheck.cs
指定されたURLのページが存在するかチェックするC#のサンプル・プログラム(pagecheck.cs)
' pagecheck.vb
Imports System
Imports System.Net
Class PageCheck
' urlにアクセスしてステータス・コードを返す
Public Shared Function GetStatusCode(ByVal url As String) As HttpStatusCode
Dim req As HttpWebRequest = _
CType(WebRequest.Create(url), HttpWebRequest)
Dim res As HttpWebResponse = Nothing
Dim statusCode As HttpStatusCode
Try
res = CType(req.GetResponse(), HttpWebResponse)
statusCode = res.StatusCode
Catch ex As WebException
res = CType(ex.Response, HttpWebResponse)
If Not res Is Nothing Then
statusCode = res.StatusCode
Else
Throw ' サーバ接続不可などの場合は再スロー
End If
Finally
If Not res Is Nothing Then
res.Close()
End If
End Try
Return statusCode
End Function
' ページが存在するかチェックするサンプル
Shared Sub Main()
Dim url As String = "http://www.atmarkit.co.jp/nosuchpage.html"
WebRequest.DefaultWebProxy = Nothing ' プロキシ未使用を明示
Dim statusCode As HttpStatusCode = GetStatusCode(url)
' 列挙体の値を数値に変換
Dim code As Integer = CType(statusCode, Integer)
If code >= 400 Then ' 4xx、5xxはアクセス失敗とする
Console.WriteLine("ページは存在しないようです:" & code)
Else
Console.WriteLine("ページは存在します:" & code)
End If
' 出力:ページは存在しないようです:404
End Sub
End Class
' コンパイル方法:vbc pagecheck.vb
指定されたURLのページが存在するかチェックするVBのサンプル・プログラム(pagecheck.vb)
Mainメソッドでは、上述のGetStatusCodeメソッドを呼び出し、その戻り値であるHttpStatusCode列挙体の値を整数に変換して、それが400以上(=HTTPステータス・コードが400番以降)である場合にはページは存在していないと判断している(なお、例外処理は省略した)。
利用可能バージョン: .NET Framework 2.0以降
カテゴリ: クラス・ライブラリ 処理対象: ネットワーク
使用ライブラリ: HttpWebRequestクラス(System.Net名前空間)
使用ライブラリ: HttpWebResponseクラス(System.Net名前空間)
使用ライブラリ: HttpStatusCodeクラス(System.Net名前空間)
使用ライブラリ: WebExceptionクラス(System.Net名前空間)
関連TIPS: WebRequest/WebResponseクラスでWebページを取得するには?
generated by
TechTargetジャパン
キャリアアップ
**先週の人気講座ランキング**
〜 Android編 〜