我正在尝试从服务器端向Facebook的Oembed endpoint发出Get请求。 当我只是在浏览器中转到URL时,它可以工作(单击此链接:https://www.facebook.com/plugins/video/oembed.json/?url=https%3A%2F%2Fwww.facebook.com%2Ffacebook%2Fvideos%2F10153231379946729%2F(
但是,从服务器端进行调用时,响应不是 json 对象。
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; }
}
想通了,你走在正确的道路上,但我必须在 HttPWebRequest 上设置 UserAgent 和 Reference 属性。我猜Facebook想确保你不是机器人。
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;
}
}
}