Contents

Accessing Google APIs through a proxy with .Net

Contents

Recently I’ve been replacing the use of Bit.ly as a link shortener with Google’s link shortener service (goo.gl) in one of our .Net projects.

It’s pretty easy to get going with their handy .Net NuGet package and sample code, however what wasn’t obvious was how to pass the HTTP requests through a proxy. After a bit of digging around, it turned out to be pretty easy:

The first thing that needs to be done is to create our own ProxySupportedHttpClientFactory class, which inherits from the Google APIs HttpClientFactory class and override the CreateHandler method to return a different handler:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
public class ProxySupportedHttpClientFactory : HttpClientFactory
{
  protected override HttpMessageHandler CreateHandler(CreateHttpClientArgs args)
  {
    var proxy = new WebProxy("http://proxyserver:8080", true, null, null);
 
    var webRequestHandler = new WebRequestHandler()
    {
      UseProxy = true,
      Proxy = proxy,
      UseCookies = false
    };
 
    return webRequestHandler;
  }
}

The next step is to then use our new ProxySupportedHttpClientFactory when creating the UrlshortenerService:

1
2
3
4
5
6
7
8
var credentials = ....
 
var linkService = new Google.Apis.Urlshortener.v1.UrlshortenerService(new BaseClientService.Initializer()
{
  HttpClientInitializer = credentials,
  ApplicationName = "MyURLThingy",
  HttpClientFactory = new ProxySupportedHttpClientFactory()
});

And that’s it.

🍪 I use Disqus for comments

Because Disqus requires cookies this site doesn't automatically load comments.

I don't mind about cookies - Show me the comments from now on (and set a cookie to remember my preference)