调用跨域 URL 时,HttpWebRequest 响应总是 text/html
HttpWebRequest response is always text/html when calling cross domain URL
我正在使用 HttpWebRequest 从跨域 (https://www.facebook.com/plugins/post/oembed.json/?url=posturl) 获取 json 结果。我已将 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();
}
我认为您还需要在请求中设置浏览器代理以获得预期结果,而不是来自 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";
我正在使用 HttpWebRequest 从跨域 (https://www.facebook.com/plugins/post/oembed.json/?url=posturl) 获取 json 结果。我已将 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();
}
我认为您还需要在请求中设置浏览器代理以获得预期结果,而不是来自 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";