Use of HttpClient in Activate
1 min
HttpClient has superseded HttpWebRequest and should be used in all new projects requiring an HTTP client.
See attached script for an example of recommended usage
Dos
- Use ProvisioningSystem.ObjectCache to reuse a single instance.
- Take advantage of the BaseAddress property, remember that this is persistent per instance
- Read HttpClient guidelines for .NET - .NET | Microsoft Learn
Don'ts
- Create and dispose with each request as each instance contains a connection pool.
Example Script
//@import System.Web;
//@import System.Linq.Expressions
//@import System.Private.Uri
//@import System.Net.Requests
//@import System.Net.WebHeaderCollection
//@import System.Collections.Specialized
//@import System.Text.Json
//@import System.Net.Http
using System;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Text.Json;
using Innovation.Activate;
using Innovation.Activate.Utilities;
class Script : ScriptBase
{
string _baseUrl = "https://jsonplaceholder.typicode.com";
string _getPostsUrl = "posts/1";
string _updatePostsUrl = "posts";
public void main()
{
RunModernExample();
// RunLegacyExample();
}
public void RunModernExample()
{
// Create the http client, or get it from the cache
HttpClient http = ProvisioningSystem.ObjectCache.GetOrCreate<HttpClient>("MY_CONNECTION",
() =>
{
var handler = new HttpClientHandler();
//Set Auth settings here
//handler.Credentials = ;
return new HttpClient(handler) { BaseAddress = new Uri(_baseUrl) };
});
// Call our endpoint
HttpResponseMessage response = AsyncUtils.ExecSync(() => http.GetAsync(_getPostsUrl));
if (!response.IsSuccessStatusCode) { return; } // Do something if the response is not successful
// Read the response to a string
string jsonString = AsyncUtils.ExecSync(() => response.Content.ReadAsStringAsync());
Trace.WriteLine(jsonString);
// Deserialise the string to an object
MyCustomResponseObject jsonObject = JsonSerializer.Deserialize<MyCustomResponseObject>(jsonString, new JsonSerializerOptions { PropertyNameCaseInsensitive = true });
Trace.WriteLine($"The user id is {jsonObject.UserId}");
// Update the object
jsonObject.Title = $"Updated: {jsonObject.Title}";
// Sent the updated object to the save enpoint
var body = new StringContent(JsonSerializer.Serialize(jsonObject), System.Text.Encoding.UTF8, "application/json");
HttpResponseMessage postResponse = AsyncUtils.ExecSync(() => http.PostAsync(_updatePostsUrl, body));
Trace.WriteLine($"The updated status code was {postResponse.StatusCode}");
}
public void RunLegacyExample()
{
HttpWebRequest request = WebRequest.Create(_baseUrl + _getPostsUrl) as HttpWebRequest;
request.Method = "GET";
//Send the request
WebResponse ws = request.GetResponse();
//Read the response
using (Stream stream = ws.GetResponseStream())
{
//Read the stream in the response
using (StreamReader reader = new StreamReader(stream, System.Text.Encoding.UTF8))
{
//Save all of the response to a string
string result = reader.ReadToEnd();
Trace.WriteLine(result);
}
}
}
}
public class MyCustomResponseObject
{
public int UserId { get; set; }
public int Id { get; set; }
public string Title { get; set; }
public string Body { get; set; }
}