Files
BeWoPlaner/Shared/ApiFacade/JsonHttpClientFacade.cs

49 lines
1.3 KiB
C#
Raw Normal View History

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using Newtonsoft.Json;
namespace BS.Shared.ApiFacade
{
public class JsonHttpClientFacade : HttpClientFacade
{
public object JsonObject { get; set; }
public JsonHttpClientFacade(string base_url, string api_key, bool directConnect = true) : base(base_url, api_key, directConnect)
{
ContentType = "application/json";
Method = HttpMethod.Post;
}
private protected override async Task<HttpResponseMessage> getResponseAsync(string method)
{
using (var client = new HttpClient { Timeout = Timeout })
{
var requestUri = BS.Shared.Core.Utilities.WebUtils.CombineUrl(Base_Url, method);
using (var request = new HttpRequestMessage(Method, requestUri))
{
await checkForDirect(request).ConfigureAwait(false);
// Add headers
foreach (var header in Headers)
request.Headers.TryAddWithoutValidation(header.Key, header.Value);
// Add body if POST or PUT
if (Method == HttpMethod.Post || Method == HttpMethod.Put)
{
var json = JsonConvert.SerializeObject(JsonObject);
request.Content = new StringContent(json, Encoding, "application/json");
}
return await client.SendAsync(request).ConfigureAwait(false);
}
}
}
}
}