Pages

Tuesday, January 20, 2015

Shortening url using google api

Today I edited a question on stackoverflow about url shortening. Looks like it was about Json serialization, and here is my solution:

 using (var client = new HttpClient())
 {
  var content = new StringContent(
   "{\"longUrl\": \"http://www.google.com/\"}",
   Encoding.UTF8,
   "application/json");

  var response = await client.PostAsync("https://www.googleapis.com/urlshortener/v1/url", content);

  var responseString = await response.Content.ReadAsStringAsync();

  var data = JsonConvert.DeserializeObject(responseString);

  var id = data.Id;
 }
And a class for urls:
 public class ShortenUrl
 {
  public string Kind { get; set; }

  public string Id { get; set; }

  public string LongUrl { get; set; }
 }
So you would have to use Newtonsoft json serializer to deserialize the json string; and HttpClient to communicate with the API