B-Arts DocumentationIndice generale

BHttp - Esempi

Richiesta GET con header

using B.BData;
using B.BNet;

List<BItem> headers = new()
{
  new BItem("Authorization", $"Bearer {token}"),
  new BItem("X-Tenant", tenantCode)
};

string json = await BHttp.BGet("https://api.example.com/orders", headers);

BGet aggiunge sempre Accept-Language: en-US. Gli elementi BItem sono convertiti in header usando Codice come nome e Descrizione come valore.

POST form-urlencoded

string response = await BHttp.Post(
  "https://api.example.com/token",
  "grant_type=client_credentials&scope=orders");

Richiesta generica JSON e proxy

using System.Collections.Specialized;

NameValueCollection headers = new()
{
  { "Authorization", $"Bearer {token}" }
};

string response = await BHttp.Request(
  "https://api.example.com/orders",
  "POST",
  "application/json",
  headers,
  "{\"customerId\":42}",
  proxyAddress: "http://proxy.example.com:8080");

Request restituisce il corpo della risposta. Non chiama EnsureSuccessStatusCode: anche una risposta HTTP di errore viene restituita come testo. Le eccezioni di rete o URL non valide non vengono intercettate.

Richiesta con verifica dell'esito HTTP

using B.BNet;
using System.Collections.Specialized;

NameValueCollection headers = new()
{
  { "Authorization", $"Bearer {token}" }
};

BHttpResponse response = await BHttp.RequestResponse(
  "https://api.example.com/orders",
  "GET",
  "",
  headers,
  "");

if (response.IsSuccess)
{
  string json = response.Content;
}
else
{
  int statusCode = response.StatusCode;
  string errorBody = response.Content;
}

RequestResponse mantiene disponibile il corpo della risposta anche quando il server restituisce un codice HTTP non riuscito. Se url è vuoto, restituisce un oggetto con valori predefiniti.

DELETE

string response = await BHttp.BDelete("https://api.example.com/orders/42");

BDelete restituisce una stringa vuota quando si verifica un'eccezione.

Client riutilizzabile e cancellazione

using BHttp http = new BHttp("http://proxy.example.com:8080");

BHttpResponse response = await http.RequestResponse(
  "https://api.example.com/orders",
  "GET", "", null, "", cancellationToken);

Usare l'istanza quando più richieste devono condividere lo stesso HttpClient. Reset() ricrea il client conservando il proxy.

Lettura streaming

await using BHttpStreamResponse response = await BHttp.RequestStreamResponse(
  "https://api.example.com/events",
  "GET", "", null, "", cancellationToken: cancellationToken);

if (response.IsSuccess && response.Stream != null)
{
  using StreamReader reader = new StreamReader(response.Stream);
  while (!reader.EndOfStream)
    Console.WriteLine(await reader.ReadLineAsync());
}
else
{
  Console.WriteLine(response.ErrorContent);
}