使用json body请求消费Rest Webservice
使用json body请求消费Rest Webservice
这是我第一次尝试使用REST Web服务。
在这个REST Web服务中,我需要创建一个头部并发送JSON格式的值。以下是我使用的代码。
var password = tb_Authorization.Text; var user = tb_AppCaller.Text; string wrURL = tb_URL.Text; WebRequest req = WebRequest.Create(tb_URL.Text); req.Method = "POST"; req.ContentType = "application/json"; req.Headers["Authorization"] = tb_Authorization.Text; req.Headers["AppCaller"] = tb_AppCaller.Text;
我需要发送以下JSON格式的内容以获取响应:
{ "lastName": "Jordan", "firstName": "Michael"}
以获取:
{
"NumCountry": 1,
"Country": [
{
"Name": "USA",
"rank": 1
}
]
}
在最后一部分,我的思维停滞了,我无法进行“下一步”。
我的基本问题是如何在头部中发送JSON数据?
问题的原因是:无法使用json请求正文调用Rest Webservice。
解决方法是:使用StreamWriter和StreamReader。
下面是解决方法的代码示例:
var httpWebRequest = (HttpWebRequest)WebRequest.Create(tb_URL.Text); httpWebRequest.ContentType = "application/json"; httpWebRequest.Method = "POST"; using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream())) { string json = "{\"lastName\": \"Jordan\", \"firstName\": \"Michael\"}"; streamWriter.Write(json); streamWriter.Flush(); streamWriter.Close(); } var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse(); using (var streamReader = new StreamReader(httpResponse.GetResponseStream())) { var result = streamReader.ReadToEnd(); }
感谢Vivek Nuna,现在这些东西对我来说更有意义了。:) 干杯。