HttpResponseMessage Classe

Definição

Representa uma mensagem de resposta HTTP que inclui o código de estado e os dados.

public ref class HttpResponseMessage : IDisposable
public class HttpResponseMessage : IDisposable
type HttpResponseMessage = class
    interface IDisposable
Public Class HttpResponseMessage
Implements IDisposable
Herança
HttpResponseMessage
Implementações

Exemplos

// HttpClient is intended to be instantiated once per application, rather than per-use. See Remarks.
static readonly HttpClient client = new HttpClient();

static async Task Main()
{
    // Call asynchronous network methods in a try/catch block to handle exceptions.
    try
    {
        using HttpResponseMessage response = await client.GetAsync("http://www.contoso.com/");
        response.EnsureSuccessStatusCode();
        string responseBody = await response.Content.ReadAsStringAsync();
        // Above three lines can be replaced with new helper method below
        // string responseBody = await client.GetStringAsync(uri);

        Console.WriteLine(responseBody);
    }
    catch (HttpRequestException e)
    {
        Console.WriteLine("\nException Caught!");
        Console.WriteLine("Message :{0} ", e.Message);
    }
}
open System.Net.Http

// HttpClient is intended to be instantiated once per application, rather than per-use. See Remarks.
let client = new HttpClient()

let main =
    task {
        // Call asynchronous network methods in a try/catch block to handle exceptions.
        try
            use! response = client.GetAsync "http://www.contoso.com/"
            response.EnsureSuccessStatusCode() |> ignore
            let! responseBody = response.Content.ReadAsStringAsync()
            // Above three lines can be replaced with new helper method below
            // let! responseBody = client.GetStringAsync uri

            printfn $"{responseBody}"
        with
        | :? HttpRequestException as e ->
            printfn "\nException Caught!"
            printfn $"Message :{e.Message} "
    }

main.Wait()
' HttpClient is intended to be instantiated once per application, rather than per-use. See Remarks.
Shared ReadOnly client As HttpClient = New HttpClient()

Private Shared Async Function Main() As Task
    ' Call asynchronous network methods in a try/catch block to handle exceptions.
    Try
        Using response As HttpResponseMessage = Await client.GetAsync("http://www.contoso.com/")
            response.EnsureSuccessStatusCode()
            Dim responseBody As String = Await response.Content.ReadAsStringAsync()
            ' Above three lines can be replaced with new helper method below
            ' Dim responseBody As String = Await client.GetStringAsync(uri)

            Console.WriteLine(responseBody)
        End Using
    Catch e As HttpRequestException
        Console.WriteLine(Environment.NewLine & "Exception Caught!")
        Console.WriteLine("Message :{0} ", e.Message)
    End Try
End Function

O exemplo de código anterior utiliza um async Task Main() ponto de entrada. Essa funcionalidade requer C# 7.1 ou posterior.

Observações

Uma forma comum de obter um HttpResponseMessage é através de um dos HttpClient.SendAsync(HttpRequestMessage) métodos.

Construtores

Name Description
HttpResponseMessage()

Inicializa uma nova instância da HttpResponseMessage classe.

HttpResponseMessage(HttpStatusCode)

Inicializa uma nova instância da HttpResponseMessage classe com um .StatusCode

Propriedades

Name Description
Content

Recebe ou define o conteúdo de uma mensagem de resposta HTTP.

Headers

Obtém a coleção de cabeçalhos de resposta HTTP.

IsSuccessStatusCode

Recebe um valor que indica se a resposta HTTP foi bem-sucedida.

ReasonPhrase

Recebe ou define a frase de razão, que normalmente é enviada pelos servidores juntamente com o código de estado.

RequestMessage

Recebe ou define a mensagem de pedido que levou a esta mensagem de resposta.

StatusCode

Obtém ou define o código de estado da resposta HTTP.

TrailingHeaders

Recebe a coleção de cabeçalhos finais incluída numa resposta HTTP.

Version

Recebe ou define a versão da mensagem HTTP.

Métodos

Name Description
Dispose()

Liberta os recursos não geridos e elimina os recursos não geridos usados pelo HttpResponseMessage.

Dispose(Boolean)

Liberta os recursos não geridos usados pelo HttpResponseMessage e opcionalmente elimina os recursos geridos.

EnsureSuccessStatusCode()

Lança uma exceção se a IsSuccessStatusCode propriedade da resposta HTTP for false.

Equals(Object)

Determina se o objeto especificado é igual ao objeto atual.

(Herdado de Object)
GetHashCode()

Serve como função de hash predefinida.

(Herdado de Object)
GetType()

Obtém o Type da instância atual.

(Herdado de Object)
MemberwiseClone()

Cria uma cópia superficial do atual Object.

(Herdado de Object)
ToString()

Devolve uma cadeia que representa o objeto atual.

Métodos da Extensão

Name Description
ToMessage(HttpResponseMessage)

Cria uma Message instância a partir de uma HttpResponseMessage instância.

Aplica-se a