Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // See https://deliverystack.net/2021/04/02/prototype-net-class-to-invoke-contentstack-saas-headless-content-management-https-json-service-apis/
- public class HttpRequestHandler
- {
- public async Task<string> ProcessRequest(
- string Url,
- JObject payloadBody = null,
- string method = null)
- {
- // URL of HTTPS API call
- WebRequest request = (HttpWebRequest)WebRequest.Create(Url);
- // if caller specified an HTTP method
- if (method != null)
- {
- request.Method = method;
- }
- // if the request has a JSON payload (query), then encode it
- // and default the HTTP method if the caller did not specify
- if (payloadBody != null)
- {
- if (request.Method == null)
- {
- request.Method = "PUT"; //TODO: or default to POST?
- }
- byte[] byteArray = Encoding.UTF8.GetBytes(payloadBody.ToString());
- request.ContentLength = byteArray.Length;
- using (Stream requestStream = request.GetRequestStream())
- {
- requestStream.Write(byteArray, 0, byteArray.Length);
- }
- }
- else
- {
- // request has no JSON payload; default HTTP method
- if (request.Method == null)
- {
- request.Method = "GET";
- }
- }
- request.ContentType = "application/json";
- // user agent can be useful for statics/reporting
- request.Headers["x-user-agent"] = this.ToString();
- //TODO: vendor-specific and shouldn't be hard-coded
- request.Headers["api_key"] = "blt1119a67aaafee1ed";
- request.Headers["authorization"] = "cs38018818305e668201bc94c3";
- // call the API and return its response as a string
- using (Stream responseStream =
- ((HttpWebResponse)await request.GetResponseAsync()).GetResponseStream())
- {
- return new StreamReader(responseStream).ReadToEnd();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement