I'm trying to make a Get request to Facebook's Oembed endpoint from server side. When I just go to the URL in my browser it works (click this link: https://www.facebook.com/plugins/video/oembed.json/?url=https%3A%2F%2Fwww.facebook.com%2Ffacebook%2Fvideos%2F10153231379946729%2F)
However, when making the call from the server side, response isn't a json object.
static void Main(string[] args)
{
string uri2 = "https://www.facebook.com/plugins/video/oembed.json/?url=https%3A%2F%2Fwww.facebook.com%2Ffacebook%2Fvideos%2F10153231379946729%2F";
CreateLinkRequest call2 = new CreateLinkRequest();
call2 = Get<CreateLinkRequest>(uri2);
Console.ReadLine();
}
public static T Get<T>(string uri)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
using (Stream stream = response.GetResponseStream())
using (StreamReader reader = new StreamReader(stream))
{
string json = reader.ReadToEnd();
Object result = new JavaScriptSerializer().Deserialize<T>(json);
return (T)result;
}
}
}
public class CreateLinkRequest
{
public string provider_name { get; set; }
public string author_name { get; set; }
public string width { get; set; }
public string author_url { get; set; }
public string title { get; set; }
public string type { get; set; }
public string version { get; set; }
public string thumbnail_width { get; set; }
public string provider_url { get; set; }
public string thumbnail_height { get; set; }
public string html { get; set; }
public int height { get; set; }
public string thumbnail_url { get; set; }
}
Figured it out, you were on the right path but I had to set the UserAgent and Refer properties on the HttPWebRequest. I guess facebook wants to make sure you're not a bot
public static T Get<T>(string uri)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.UserAgent = "Mozilla / 5.0(Windows; U; WindowsNT 5.1; en - US; rv1.8.1.6) Gecko / 20070725 Firefox / 2.0.0.6";
request.Referer = "http://www.google.com";
request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
using (Stream stream = response.GetResponseStream())
using (StreamReader reader = new StreamReader(stream))
{
string json = reader.ReadToEnd();
Object result = new JavaScriptSerializer().Deserialize<T>(json);
return (T)result;
}
}
}