Skip to content

Instantly share code, notes, and snippets.

@mpoerwito
Last active November 8, 2022 16:33
Show Gist options
  • Save mpoerwito/2ef2ef7396d6dcfba8a07a6e40927b06 to your computer and use it in GitHub Desktop.
Save mpoerwito/2ef2ef7396d6dcfba8a07a6e40927b06 to your computer and use it in GitHub Desktop.
Simple API client
using System;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using System.Runtime.Serialization.Json;
using Client.Entities;
namespace Client
{
public class APIClient
{
public string RawData { get; set; }
public string ClientID { get; set; }
public string ClientSecret { get; set; }
public string HostName { get; set; }
public APIClient(string Host, string User, string Password)
{
HostName = Host;
ClientID = User;
ClientSecret = Password;
}
public async Task<string[]> PostContent(string Path, string JSONBody)
{
string[] result = new string[3];
UriBuilder uri = new UriBuilder
{
Scheme = "https",
Port = -1,
Host = HostName,
Path = Path
};
var byteArray = new System.Text.UTF8Encoding().GetBytes($"{ClientID}:{ClientSecret}");
using (var client = new HttpClient())
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
var response = await client.PostAsync(uri.ToString(), new StringContent(JSONBody, System.Text.Encoding.Unicode, "application/json"));
if (response.IsSuccessStatusCode)
{
RawData = response.Content.ReadAsStringAsync().Result;
using var ms = new MemoryStream(System.Text.Encoding.Unicode.GetBytes(RawData));
DataContractJsonSerializer ds = new DataContractJsonSerializer(typeof(PostResponse));
PostResponse presp = (PostResponse)ds.ReadObject(ms);
result[0] = presp.PO_DATA.BATCH_NUMBER;
result[1] = presp.PO_DATA.PO_HEADER.Count.ToString();
result[2] = presp.PO_DATA.CUSTOMER_NAME;
}
else
{
result[0] = response.StatusCode.ToString();
result[1] = response.ReasonPhrase;
result[2] = "0";
}
}
return result;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment