Accendo / Publikované

Rest Client

Autor:   Libor Bešenyi

Dátum: 19.7.2012

 

Rest is communication protocol for B2B / G2B architectures (same as Soap). Rest is derived from http, so we can very simply downloading data from server or uploading to 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 there is needed to use server side certificates. They are usually in P12 format. For P12 certificates we need to have passwords. 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 expects in http header authorization parameter. It is usually encoded in base64. We need to add to response another line:

request.Headers[HttpRequestHeader.Authorization] =

"Basic " + Convert.ToBase64String(System.Text.Encoding.Unicode.GetBytes(???));

 

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

request.Method = WebRequestMethods.Http.Put;

 

var base64Content = toBase64Content ?

       System.Text.Encoding.Unicode.GetBytes(Convert.ToBase64String(content)) :

content;

 

request.ContentType = contentType;

request.ContentLength = base64Content.Length;

using (var requestStream = request.GetRequestStream())

       requestStream.Write(base64Content, /*offset*/0, base64Content.Length);