Skip to content

Instantly share code, notes, and snippets.

View ByteDev's full-sized avatar
:octocat:

ByteDev

:octocat:
View GitHub Profile
var response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);
public class JsonContent : StringContent
{
    public JsonContent(string content)
        : this(content, Encoding.UTF8)
    {
    }

    public JsonContent(string content, Encoding encoding)
 : base(content, encoding, "application/json")
var request = new HttpRequestMessage(HttpMethod.Post, "api/orders");

request.Content = new JsonContent(json);
var response = await client.SendAsync(request);

if (response.StatusCode == HttpStatusCode.Unauthorized)
{
    // need to refresh the request security token!
}

if (response.IsSuccessStatusCode)
{
var response = await client.SendAsync(request);

if (response.StatusCode == HttpStatusCode.BadRequest)
{
    var details = await response.Content.ReadAsStringAsync();
}
var response = await client.SendAsync(request);

if (response.Content.Headers.ContentType.MediaType == "application/json")
{
    var json = await response.Content.ReadAsStringAsync();
  
    var order = JsonConvert.DeserializeObject<Order>(json);
}
public async Task<Order> GetOrderAsync(CancellationToken cancellationToken = default)
{
    // setup your client & request
  
    var response = await client.SendAsync(request, cancellationToken);
}
// Tell HttpClient to auto decompress responses using the 
// particular compression method (e.g. GZip).
var client = new HttpClient(new HttpClientHandler
{
    AutomaticDecompression = DecompressionMethods.GZip
});

// ...
var response = await client.SendAsync(request);

using(var stream = await response.Content.ReadAsStreamAsync())
{
    using (var streamReader = new StreamReader(stream))
    {
      using (var jsonTextReader = new JsonTextReader(streamReader))
      {
 var customer = new JsonSerializer().Deserialize(jsonTextReader); 
public class FakeResponseHandler : HttpMessageHandler
{
    private readonly HttpStatusCode _httpStatusCode;
    private readonly HttpContent _httpContent;

    public FakeResponseHandler(HttpStatusCode httpStatusCode) : this(httpStatusCode, null)
    {
    }