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 usa il client statico BHttp.Client e restituisce una stringa vuota quando si verifica un'eccezione.
