Skip to content

HttpClient Configuration

Don Kackman edited this page Feb 7, 2015 · 1 revision

The DynamicRestClient uses the System.Net.Http.HttpClient for communication. In most cases the HttpClient is managed internally by the rest client. It is possible to control the configuration of the HttpClient.

DynamicRestClientDefaults

A set of default data can be used when constructing the DynamicRestClient that will be used to configure the HttpClient and/or control each request subsequently made. This includes default headers, default parameters, user agent string, and auth token. In addition to allowing finer grained control over the request headers, it also allows api specific parameters to be added to every request.

var key = CredentialStore.RetrieveObject("flickr.key.json");
var defaults = new DynamicRestClientDefaults();
defaults.DefaultParameters.Add("format", "json");
defaults.DefaultParameters.Add("api_key", key.Key);
defaults.DefaultParameters.Add("nojsoncallback", "1");

using (dynamic client = new DynamicRestClient("https://api.flickr.com/services/rest/", defaults))
{
    dynamic result = await client.get(method: "flickr.people.findByUsername", username: "dkackman");
    Assert.IsNotNull(result);
    Assert.AreEqual("9039518@N03", result.user.id);
}

Creating the HttpClient First

An instance of the HttpClient can be passed to the DynamicRestClient in one of its constructors. When this is done the caller can completely configure the client before hand. This client instance is used for communication.

var handler = new HttpClientHandler();
if (handler.SupportsAutomaticDecompression)
{
    handler.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
}

var client = new HttpClient(handler, true);
client.BaseAddress = new Uri("http://dev.virtualearth.net/REST/v1/");

string key = CredentialStore.Key("bing");

using (dynamic proxy = new DynamicRestClient(client, true))
{
    var result = await proxy.Locations.get(postalCode: "55116", countryRegion: "US", key: key);

    Assert.AreEqual(result.statusCode, 200);
    Assert.IsTrue(result.resourceSets.Count > 0);
    Assert.IsTrue(result.resourceSets[0].resources.Count > 0);

    var r = result.resourceSets[0].resources[0].point.coordinates;
    Assert.IsTrue((44.9108238220215).AboutEqual((double)r[0]));
    Assert.IsTrue((-93.1702041625977).AboutEqual((double)r[1]));
}

Clone this wiki locally