Imports System.Net
NotInheritable Class Program
Private Sub New()
End Sub
Private Shared Sub Main()
Using client As New MyClient()
client.HeadOnly = True
Dim uri As String = "http://www.google.com"
Dim body As Byte() = client.DownloadData(uri)
' note should be 0-length
Dim type As String = client.ResponseHeaders("content-type")
client.HeadOnly = False
' check 'tis not binary... we'll use text/, but could
' check for text/html
If type.StartsWith("text/") Then
Dim text As String = client.DownloadString(uri)
Console.WriteLine(text)
End If
End Using
End Sub
End Class
Class MyClient
Inherits WebClient
Public Property HeadOnly() As Boolean
Get
Return m_HeadOnly
End Get
Set
m_HeadOnly = Value
End Set
End Property
Private m_HeadOnly As Boolean
Protected Overrides Function GetWebRequest(address As Uri) As WebRequest
Dim req As WebRequest = MyBase.GetWebRequest(address)
If HeadOnly AndAlso req.Method = "GET" Then
req.Method = "HEAD"
End If
Return req
End Function
End Class
Code (C#)
using System;
using System.Net;
static class Program
{
static void Main()
{
using (MyClient client = new MyClient())
{
client.HeadOnly = true;
string uri = "http://www.google.com";
byte[] body = client.DownloadData(uri); // note should be 0-length
string type = client.ResponseHeaders["content-type"];
client.HeadOnly = false;
// check 'tis not binary... we'll use text/, but could
// check for text/html
if (type.StartsWith(@"text/"))
{
string text = client.DownloadString(uri);
Console.WriteLine(text);
}
}
}
}
class MyClient : WebClient
{
public bool HeadOnly { get; set; }
protected override WebRequest GetWebRequest(Uri address)
{
WebRequest req = base.GetWebRequest(address);
if (HeadOnly && req.Method == "GET")
{
req.Method = "HEAD";
}
return req;
}
}