这段代码有效,但可能只和112岁的酒鬼一样好:
try
{
const string uri = "http://localhost:28642/api/departments/Count";
var webRequest = (HttpWebRequest)WebRequest.Create(uri);
webRequest.Method = "GET";
var webResponse = (HttpWebResponse)webRequest.GetResponse();
if ((webResponse.StatusCode == HttpStatusCode.OK) && (webResponse.ContentLength > 0))
{
var reader = new StreamReader(webResponse.GetResponseStream());
string s = reader.ReadToEnd();
MessageBox.Show(string.Format("Content from HttpWebRequest is {0}", s));
}
else
{
MessageBox.Show(string.Format("Status code == {0}", webResponse.StatusCode));
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
被调用的 Web API REST 方法仅返回一个 int。这个 StreamReader 爵士乐是否为了获得这个简单的值而矫枉过正?如果是这样,首选方法是什么?
Jon Skeet 在案子上 - WebClient.DownloadString 很容易(吃)馅饼:
var client = new WebClient();
MessageBox.Show(client.DownloadString("http://localhost:28642/api/departments/Count"));
IOW,我最初显示的代码对于检索标量值来说绝对是矫枉过正的。
更新
更好的是:
private void buttonGetDeptCount2_Click(object sender, EventArgs e)
{
MessageBox.Show(GetScalarVal("http://localhost:28642/api/departments/Count"));
}
private string GetScalarVal(string uri)
{
var client = new WebClient();
return client.DownloadString(uri);
}