Skip to content

Instantly share code, notes, and snippets.

@alensiljak
Created October 11, 2012 13:49
Show Gist options
  • Save alensiljak/3872431 to your computer and use it in GitHub Desktop.
Save alensiljak/3872431 to your computer and use it in GitHub Desktop.
Custom Web Client with support for GZip compression and cookies (authentication)
using System;
using System.Collections.Generic;
using System.Net;
using System.Text;
namespace MyNamespace
{
/// <summary>
/// This web client supports Gzip compression and authentication.
/// </summary>
public class CustomWebClient : WebClient
{
public CustomWebClient()
{
AuthenticationTicket = string.Empty;
LocationCode = string.Empty;
}
public string AuthenticationTicket { get; set; }
public string LocationCode { get; set; }
private void AddAuthenticationCookies(Uri path)
{
var c = CookieContainer;
// example how to add pre-set cookies.
// c.Add(new Cookie(".AUTH", AuthenticationTicket, "", path.DnsSafeHost));
}
private CookieContainer _cookieContainer;
public CookieContainer CookieContainer
{
get
{
return _cookieContainer ?? (_cookieContainer = new CookieContainer());
}
set { _cookieContainer = value; }
}
protected override WebRequest GetWebRequest(Uri address)
{
var request = (HttpWebRequest)base.GetWebRequest(address);
if (request != null)
{
request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
// set up cookies
AddAuthenticationCookies(address);
request.CookieContainer = this.CookieContainer;
}
return request;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment