调用跨域URL时,HttpWebRequest响应始终为text/html

Jam*_*mes 2 c# rest cross-domain

我正在使用HttpWebRequest从跨域获取json结果(https://www.facebook.com/plugins/post/oembed.json/?url=posturl).我已将ContentType和Accept设置为application/json,但我总是得到text/html响应.预期的结果是JSON.

string result = string.Empty;
var request = (HttpWebRequest)WebRequest.Create("https://www.facebook.com/plugins/post/oembed.json/?url=xxxxxx");

request.ContentType = "application/json; charset=utf-8";
request.Accept = "application/json";
request.Method = "POST";                

var response = (HttpWebResponse)request.GetResponse();
using (var streamReader = new StreamReader(response.GetResponseStream()))
{
    result = streamReader.ReadToEnd();
}
Run Code Online (Sandbox Code Playgroud)

Dan*_*und 5

我认为您还需要在请求中设置浏览器代理以获得预期结果,而不是来自Facebook的嵌入式HTML.

就像是:

request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/15.0.874.121 Safari/535.2";
Run Code Online (Sandbox Code Playgroud)