Knowledge base

IT is a great and exciting world to be in.
All who have passion for it will understand why we have created these pages.
Here we share our technical knowledge with you.
ProgrammingAICloudManagementMobileDB & AnalysisSafetyOtherArchitectureTips

C# Rest Client

 Libor Bešenyi (Solution architect)

Rest is a communication protocol for B2B / G2B architectures (same as Soap). Rest is derived from http, so we can very simply download data from a server or upload them to a server.

Download is standard Get operation:

var request = (HttpWebRequest)WebRequest.Create(testUrl);

request.Method = WebRequestMethods.Http.Get;
request.Accept = acceptResponse;

WebResponse response;
try // catch
{
       response = request.GetResponse();
} // try
catch (WebException e)
{
       if (e.Response == null)
             throw; // Protocol exception

       response = e.Response;
} // catch

try // finally
{
       using (var responseStream = response.GetResponseStream())
       {
             using (var responseReader = new StreamReader(responseStream))
             {
                    // ((HttpWebResponse)response).StatusCode == HttpStatusCode.OK;
                    var responseContent = responseReader.ReadToEnd();

                    // ???
             } // using
       } // using
} // try
finally
{
       response.Close();
} // finally

This is very simple. Sometimes it is necessary to use server side certificates. They are usually in P12 format. We need to have passwords for P12 certificates. Adding certificates is very simple:

request.ClientCertificates.Clear();

if (!string.IsNullOrEmpty(certificateFileName))
{
       var certificate = new X509Certificate2();
       certificate.Import(certificateFileName, password, X509KeyStorageFlags.DefaultKeySet);

       request.ClientCertificates.Add(certificate);
} // if

Some web servers expect authorization parameter in http header. It is usually encoded in base64. We need to add a response to another line:

request.Headers[HttpRequestHeader.Authorization] = "Basic " + Convert.ToBase64String(System.Text.Encoding.Unicode.GetBytes(???));

PUT (or POST) http method is used for sending data (usually in XML format) to a server:

request.Method = WebRequestMethods.Http.Put;

var base64Content = toBase64Content ? System.Text.Encoding.Unicode.GetBytes(Convert.ToBase64String(content)) : content;
request.ContentLength = base64Content.Length;
request.ContentType = contentType;

using (var requestStream = request.GetRequestStream())
       requestStream.Write(base64Content, /*offset*/0, base64Content.Length);

 

Find out more

ProgrammingArchitectureTips

Quick start

1
Contact
Contact us for a free consultation on your business needs!
2
Analysis
After the discussion we will perform mapping of the processes and analyse the current state.
3
Proposal
You will receive variety of scenarios to choose from discribing different ways how to solve your issue.
Contact us