如何在C#中使用system.net.webrequest得到JSON响应?如何在、system、net、webrequest

2023-09-02 01:44:11 作者:离心离情

我需要从外部域获取JSON数据。 我用的WebRequest获取从网站的响应。 这里的code:

I need to get json data from an external domain. I used webrequest to get the response from a website. Here's the code:

var request = WebRequest.Create(url);
string text;
var response = (HttpWebResponse) request.GetResponse();

using (var sr = new StreamReader(response.GetResponseStream()))
{
    text = sr.ReadToEnd();
}

任何人都知道,为什么我不能得到的JSON数据?

Anyone know why I can't get the json data?

推荐答案

您需要明确要求的内容类型。

You need to explicitly ask for the content type.

添加此行:

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

在适当的地方

At the appropriate place