简体   繁体   English

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

[英]HttpWebRequest response is always text/html when calling cross domain URL

I am using HttpWebRequest to get json result from a cross domain ( https://www.facebook.com/plugins/post/oembed.json/?url=posturl ). 我正在使用HttpWebRequest从跨域( https://www.facebook.com/plugins/post/oembed.json/?url=posturl )获取json结果。 I have set ContentType and Accept to application/json, but I always get a text/html response. 我已经将ContentType和Accept设置为application / json,但是我总是收到text / html响应。 Expected result is JSON. 预期结果是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();
}

I think you also need to set a browser agent in your request to get the expected results and not the embedded HTML from Facebook. 我认为您还需要在请求中设置浏览器代理,以获取预期结果,而不是从Facebook获得嵌入式HTML。

Something like: 就像是:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM