Advertisement
commodore73

.NET HTTP Request processor to call JSON service APIs

Apr 2nd, 2021 (edited)
142
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.04 KB | None | 0 0
  1. // See https://deliverystack.net/2021/04/02/prototype-net-class-to-invoke-contentstack-saas-headless-content-management-https-json-service-apis/
  2.  
  3. public class HttpRequestHandler
  4. {
  5.     public async Task<string> ProcessRequest(
  6.         string Url,
  7.         JObject payloadBody = null,
  8.         string method = null)
  9.     {
  10.         // URL of HTTPS API call
  11.         WebRequest request = (HttpWebRequest)WebRequest.Create(Url);
  12.  
  13.         // if caller specified an HTTP method
  14.         if (method != null)
  15.         {
  16.             request.Method = method;
  17.         }
  18.  
  19.         // if the request has a JSON payload (query), then encode it
  20.         // and default the HTTP method if the caller did not specify
  21.         if (payloadBody != null)
  22.         {
  23.             if (request.Method == null)
  24.             {
  25.                 request.Method = "PUT"; //TODO: or default to POST?
  26.             }
  27.  
  28.             byte[] byteArray = Encoding.UTF8.GetBytes(payloadBody.ToString());
  29.             request.ContentLength = byteArray.Length;
  30.  
  31.             using (Stream requestStream = request.GetRequestStream())
  32.             {
  33.                 requestStream.Write(byteArray, 0, byteArray.Length);
  34.             }
  35.         }
  36.         else
  37.         {
  38.             // request has no JSON payload; default HTTP method
  39.             if (request.Method == null)
  40.             {
  41.                 request.Method = "GET";
  42.             }
  43.         }
  44.  
  45.         request.ContentType = "application/json";
  46.  
  47.         // user agent can be useful for statics/reporting
  48.         request.Headers["x-user-agent"] = this.ToString();
  49.  
  50.         //TODO: vendor-specific and shouldn't be hard-coded
  51.         request.Headers["api_key"] = "blt1119a67aaafee1ed";
  52.         request.Headers["authorization"] = "cs38018818305e668201bc94c3";
  53.  
  54.         // call the API and return its response as a string
  55.         using (Stream responseStream =
  56.             ((HttpWebResponse)await request.GetResponseAsync()).GetResponseStream())
  57.         {
  58.             return new StreamReader(responseStream).ReadToEnd();
  59.         }
  60.     }
  61. }
  62.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement