简体   繁体   中英

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 ). I have set ContentType and Accept to application/json, but I always get a text/html response. Expected result is 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.

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";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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