HttpResponseMessage Classe

Definição

Representa uma mensagem de resposta HTTP, incluindo o código de status 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 usa um async Task Main() ponto de entrada. Esse recurso requer C# 7.1 ou posterior.

Comentários

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

Construtores

Nome Description
HttpResponseMessage()

Inicializa uma nova instância da classe HttpResponseMessage.

HttpResponseMessage(HttpStatusCode)

Inicializa uma nova instância da HttpResponseMessage classe com uma específica StatusCode.

Propriedades

Nome Description
Content

Obtém ou define o conteúdo de uma mensagem de resposta HTTP.

Headers

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

IsSuccessStatusCode

Obtém um valor que indica se a resposta HTTP foi bem-sucedida.

ReasonPhrase

Obtém ou define a frase de motivo, que normalmente é enviada por servidores junto com o código de status.

RequestMessage

Obtém ou define a mensagem de solicitação que levou a essa mensagem de resposta.

StatusCode

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

TrailingHeaders

Obtém a coleção de cabeçalhos à direita incluídos em uma resposta HTTP.

Version

Obtém ou define a versão da mensagem HTTP.

Métodos

Nome Description
Dispose()

Libera os recursos não gerenciados e descarta os recursos não gerenciados usados pelo HttpResponseMessage.

Dispose(Boolean)

Libera os recursos não gerenciados usados pelos HttpResponseMessage recursos gerenciados e, opcionalmente, descartados.

EnsureSuccessStatusCode()

Gera uma exceção se a IsSuccessStatusCode propriedade para a resposta HTTP for false.

Equals(Object)

Determina se o objeto especificado é igual ao objeto atual.

(Herdado de Object)
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)
ToString()

Retorna uma cadeia de caracteres que representa o objeto atual.

Métodos de Extensão

Nome Description
ToMessage(HttpResponseMessage)

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

Aplica-se a