I am using the WebClient.DownloadString() method to download some data. I am using the following code:
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();
}
With this code, tt works fine and gives me an xml string as the output. But I would like to get a JSON output and hence I un-commented the line
queries.Add("output", "sparql_json");
and executed the same program and it seems to be fetching an error message from the server.
However, if I try to use a web browser and use the same url (as given below), it gives me a JSON as expected: URL that works in browsers
I am wondering what the problem could be. Especially when it works in a browser and not using a webclient. Is the webclient doing something different here?
Please note that I also tried to specify the query as
query + "&output=sparql_json"
But that does not work either.
Could someone please tell me what the problem might be?
Thanks
Add wc.Headers.Add("Accept","application/json");
. Here is the full source I tested
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 = "..."
initialization, should you be encoding the value already? I don't think you should be. Put it as plain-text and letqueries.Add("query", query)
encode it for you - Matthew 2012-04-05 17:08