C# WebClient.DownloadString(url)不适用于第二个参数

C# WebClient.DownloadString(url)不适用于第二个参数,c#,download,webclient,C#,Download,Webclient,我正在使用WebClient.DownloadString()方法下载一些数据。我正在使用以下代码: static void Main(string[] args) { string query = "select+%3farticle+%3fmesh+where+{+%3farticle+a+npg%3aArticle+.+%3farticle+npg%3ahasRecord+[+dc%3asubject+%3fmesh+]+.+filter+regex%28%3fme

我正在使用WebClient.DownloadString()方法下载一些数据。我正在使用以下代码:

static void Main(string[] args)
    {
        string query = "select+%3farticle+%3fmesh+where+{+%3farticle+a+npg%3aArticle+.+%3farticle+npg%3ahasRecord+[+dc%3asubject+%3fmesh+]+.+filter+regex%28%3fmesh%2c+\"blood\"%2c+\"i\"%29+}";
        NameValueCollection queries = new NameValueCollection();
        queries.Add("query", query);
        //queries.Add("output", "sparql_json");
        using (WebClient wc = new WebClient())
        {
            wc.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");
            wc.QueryString = queries;
            string result = wc.DownloadString("http://data.nature.com/sparql");
            Console.WriteLine(result);
        }
        Console.ReadLine();
    }
有了这段代码,tt工作得很好,并给我一个xml字符串作为输出。但我希望得到一个JSON输出,因此我取消了对该行的注释

queries.Add("output", "sparql_json");
并且执行了相同的程序,它似乎从服务器获取了一条错误消息

但是,如果我尝试使用web浏览器并使用相同的url(如下所示),它会按预期为我提供JSON:

我想知道可能是什么问题。尤其是当它在浏览器中工作而不使用webclient时。网络客户端在这里做了什么不同的事情吗

请注意,我还尝试将查询指定为

query+”&output=sparql\u json“

但这也不起作用

有人能告诉我可能是什么问题吗

谢谢

Add
wc.Headers.Add(“Accept”,“application/json”)。这是我测试的完整源代码

string query = "select ?article ?mesh where { ?article a npg:Article . ?article npg:hasRecord [ dc:subject ?mesh ] . filter regex(?mesh, \"blood\", \"i\") }";
NameValueCollection queries = new NameValueCollection();
queries.Add("query", query);
queries.Add("output", "sparql_json");
using (WebClient wc = new WebClient())
{
    wc.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");
    wc.Headers.Add("Accept","application/json");
    wc.QueryString = queries;
    string result = wc.DownloadString("http://data.nature.com/sparql");
    Console.WriteLine(result);
}
Console.ReadLine();

string查询=“…”
初始化中,是否应该已经对值进行编码?我认为你不应该这样。将其作为纯文本,让
查询。添加(“查询”,query)
为您编码。Matthew,问题不在于查询。只需查询,它就可以很好地工作——它为我提供了一个xml。但是,如果我尝试在查询时执行“&output=sparql_json”,就会得到一个错误。有什么想法吗?可能是浏览器自动为您修复了一个错误的查询字符串,非常确定需要修复的是您的查询字符串。Matthew,非常感谢您的评论。显然,正如L.B所建议的,我只需要包含Accept Json头,而不做任何更改。查询字符串(编码或不编码)给出了相同的结果。很高兴您能让它工作。这太神奇了。我以前下载过一个json,但我从未指定过标题;这和服务器有什么关系吗?不管怎样,这个解决方案奏效了。谢谢!!要添加到我之前的评论中,解决方案是添加您建议的额外标题:wc.Headers.add(“Accept”,“application/json”);让一切变得不同。谢谢