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

标签 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%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: URL that works in browsers

我想知道问题出在哪里。特别是当它在浏览器中运行而不使用网络客户端时。网络客户端在这里做了什么不同的事情吗?

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

查询+“&output=sparql_json”

但这也不起作用。

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

谢谢

最佳答案

添加wc.Headers.Add("接受","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();

关于c# - WebClient.DownloadString(url) 不适用于第二个参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10032868/

相关文章:

VS2008 和 IIS6 之间的 C# 转换不同

c# - 使用 JQuery 获取列表框中的所有列表项?

c# - WebClient.UploadValues 到 WebClient.UploadValuesAsync

c# - 使用 MemoryStream 通过 WebClient Post 发送 XML

c# - 如何在 C# 中使用嵌套字典?

c# - 如何从运行在 Windows 10 Creators Update 上的 WPF 应用注册 BLE 通知?

grails - grails,如何强制浏览器下载文件

java - 如何在 wicket 中使用 zip 文件下载更大的文件?

java - 从 Restful Web 服务下载 pdf

c# - 区分多个 webclient 结果