Ram*_*Ram 2 c# webclient download
我正在使用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();
}
Run Code Online (Sandbox Code Playgroud)
使用此代码,tt工作正常,并给我一个xml字符串作为输出.但我想得到一个JSON输出,因此我没有评论该行
queries.Add("output", "sparql_json");
Run Code Online (Sandbox Code Playgroud)
并执行相同的程序,似乎从服务器获取错误消息.
但是,如果我尝试使用Web浏览器并使用相同的URL(如下所示),它会按预期提供JSON: 在浏览器中有效的URL
我想知道问题是什么.特别是当它在浏览器中工作而不使用webclient时.webclient在这里做了哪些不同的事情?
请注意,我也尝试将查询指定为
query + "&output=sparql_json"
但这也不起作用.
有人可以告诉我问题可能是什么?
谢谢
添加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();
Run Code Online (Sandbox Code Playgroud)