0

我正在尝试运行示例 WebRequest 以返回 JSON 数据。我不断收到 XML 响应。知道为什么吗?

        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);
                }
            }
        }
    }
4

1 回答 1

2

您需要将请求中的 Accept 标头设置为“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";
于 2013-05-21T21:30:25.540 回答