Reputation: 2382
I am trying to run a sample WebRequest to return JSON data. I keep on getting XML response. any idea why?
this.btnGetCoordinates.TouchUpInside += (sender, e) => {
var rxcui = "198440";
var request = HttpWebRequest.Create(string.Format (@"http://rxnav.nlm.nih.gov/REST/RxTerms/rxcui/{0}/allinfo", rxcui));
request.Method = "GET";
request.ContentType = "application/json";
request.BeginGetResponse(new AsyncCallback(ProcessGetCoordinates), request);
};
return true;
}
void ProcessGetCoordinates(IAsyncResult iar) {
HttpWebRequest request = (HttpWebRequest)iar.AsyncState;
using (HttpWebResponse response = (HttpWebResponse)request.EndGetResponse (iar)) {
if (response.StatusCode != HttpStatusCode.OK) {
Console.Out.WriteLine("Error fetching data. Server returned status code: {0}", response.StatusCode);
}
using (StreamReader strm = new StreamReader (response.GetResponseStream())) {
string content = strm.ReadToEnd ();
if (string.IsNullOrWhiteSpace (content)) {
Console.Out.WriteLine("Response contained empty body...");
} else {
Console.Out.WriteLine("Response Body: \r\n {0}", content);
}
}
}
}
Upvotes: 0
Views: 1233
Reputation: 89214
You need to set the Accept header on your request to "application/json".
var request = HttpWebRequest.Create(string.Format (@"http://rxnav.nlm.nih.gov/REST/RxTerms/rxcui/{0}/allinfo", rxcui));
request.Method = "GET";
request.Accept = "application/json";
Upvotes: 2