HttpListener Classe
Definição
Importante
Algumas informações se referem a produtos de pré-lançamento que podem ser substancialmente modificados antes do lançamento. A Microsoft não oferece garantias, expressas ou implícitas, das informações aqui fornecidas.
Fornece um ouvinte de protocolo HTTP simples e controlado programaticamente. Essa classe não pode ser herdada.
public ref class HttpListener sealed : IDisposable
public sealed class HttpListener : IDisposable
type HttpListener = class
interface IDisposable
Public NotInheritable Class HttpListener
Implements IDisposable
- Herança
-
HttpListener
- Implementações
Exemplos
// This example requires the System and System.Net namespaces.
public static void SimpleListenerExample(string[] prefixes)
{
if (!HttpListener.IsSupported)
{
Console.WriteLine ("Windows XP SP2 or Server 2003 is required to use the HttpListener class.");
return;
}
// URI prefixes are required,
// for example "http://contoso.com:8080/index/".
if (prefixes == null || prefixes.Length == 0)
throw new ArgumentException("prefixes");
// Create a listener.
HttpListener listener = new HttpListener();
// Add the prefixes.
foreach (string s in prefixes)
{
listener.Prefixes.Add(s);
}
listener.Start();
Console.WriteLine("Listening...");
// Note: The GetContext method blocks while waiting for a request.
HttpListenerContext context = listener.GetContext();
HttpListenerRequest request = context.Request;
// Obtain a response object.
HttpListenerResponse response = context.Response;
// Construct a response.
string responseString = "<HTML><BODY> Hello world!</BODY></HTML>";
byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString);
// Get a response stream and write the response to it.
response.ContentLength64 = buffer.Length;
System.IO.Stream output = response.OutputStream;
output.Write(buffer,0,buffer.Length);
// You must close the output stream.
output.Close();
listener.Stop();
}
Public Shared Sub SimpleListenerExample(prefixes As String())
If Not HttpListener.IsSupported Then
Console.WriteLine("Windows XP SP2 or Server 2003 is required to use the HttpListener class.")
Return
End If
' URI prefixes are required,
' for example "http://contoso.com:8080/index/".
If prefixes Is Nothing Or prefixes.Length = 0 Then
Throw New ArgumentException("prefixes")
End If
' Create a listener
Dim listener = New HttpListener()
For Each s As String In prefixes
listener.Prefixes.Add(s)
Next
listener.Start()
Console.WriteLine("Listening...")
' Note: The GetContext method blocks while waiting for a request.
Dim context As HttpListenerContext = listener.GetContext()
Console.WriteLine("Listening...")
' Obtain a response object
Dim request As HttpListenerRequest = context.Request
' Construct a response.
Dim response As HttpListenerResponse = context.Response
Dim responseString As String = "<HTML><BODY> Hello world!</BODY></HTML>"
Dim buffer As Byte() = System.Text.Encoding.UTF8.GetBytes(responseString)
' Get a response stream and write the response to it.
response.ContentLength64 = buffer.Length
Dim output As System.IO.Stream = response.OutputStream
output.Write(buffer, 0, buffer.Length)
'You must close the output stream.
output.Close()
listener.Stop()
End Sub
Comentários
Para obter mais informações sobre essa API, consulte comentários da API Complementar para HttpListener.
Construtores
| Nome | Description |
|---|---|
| HttpListener() |
Inicializa uma nova instância da classe HttpListener. |
Propriedades
| Nome | Description |
|---|---|
| AuthenticationSchemes |
Obtém ou define o esquema usado para autenticar clientes. |
| AuthenticationSchemeSelectorDelegate |
Obtém ou define o delegado chamado para determinar o protocolo usado para autenticar clientes. |
| DefaultServiceNames |
Obtém uma lista padrão de SPNs (Nomes do Provedor de Serviços), conforme determinado por prefixos registrados. |
| ExtendedProtectionPolicy |
Obtém ou define o ExtendedProtectionPolicy uso para proteção estendida para uma sessão. |
| ExtendedProtectionSelectorDelegate |
Obtém ou define o delegado chamado para determinar o ExtendedProtectionPolicy uso para cada solicitação. |
| IgnoreWriteExceptions |
Obtém ou define um Boolean valor que especifica se seu aplicativo recebe exceções que ocorrem quando uma HttpListener resposta é enviada ao cliente. |
| IsListening |
Obtém um valor que indica se HttpListener foi iniciado. |
| IsSupported |
Obtém um valor que indica se HttpListener pode ser usado com o sistema operacional atual. |
| Prefixes |
Obtém os prefixos de URI (Uniform Resource Identifier) manipulados por esse HttpListener objeto. |
| Realm |
Obtém ou define o realm, ou partição de recurso, associado a esse HttpListener objeto. |
| TimeoutManager |
O gerenciador de tempo limite para essa HttpListener instância. |
| UnsafeConnectionNtlmAuthentication |
Obtém ou define um Boolean valor que controla se, quando o NTLM é usado, solicitações adicionais usando a mesma conexão TCP (Protocolo de Controle de Transmissão) são necessárias para autenticação. |
Métodos
| Nome | Description |
|---|---|
| Abort() |
Desliga o HttpListener objeto imediatamente, descartando todas as solicitações na fila no momento. |
| BeginGetContext(AsyncCallback, Object) |
Começa a recuperar de forma assíncrona uma solicitação de entrada. |
| Close() |
Desliga o HttpListener. |
| EndGetContext(IAsyncResult) |
Conclui uma operação assíncrona para recuperar uma solicitação de cliente de entrada. |
| Equals(Object) |
Determina se o objeto especificado é igual ao objeto atual. (Herdado de Object) |
| GetContext() |
Aguarda uma solicitação de entrada e retorna quando uma é recebida. |
| GetContextAsync() |
Aguarda uma solicitação de entrada como uma operação assíncrona. |
| GetHashCode() |
Serve como a função hash predefinida. (Herdado de Object) |
| GetType() |
Obtém o Type da instância atual. (Herdado de Object) |
| MemberwiseClone() |
Cria uma cópia superficial do Objectatual. (Herdado de Object) |
| Start() |
Permite que essa instância receba solicitações de entrada. |
| Stop() |
Faz com que essa instância pare de receber novas solicitações de entrada e encerre o processamento de todas as solicitações em andamento. |
| ToString() |
Retorna uma cadeia de caracteres que representa o objeto atual. (Herdado de Object) |
Implantações explícitas de interface
| Nome | Description |
|---|---|
| IDisposable.Dispose() |
Libera os recursos mantidos por esse HttpListener objeto. |