从asp.net C调用外部json Web服务#
我需要从C#Asp.net调用json Web服务。服务返回一个json对象,Web服务想要的json数据如下所示:从asp.net C调用外部json Web服务#,asp.net,web-services,json,Asp.net,Web Services,Json,我需要从C#Asp.net调用json Web服务。服务返回一个json对象,Web服务想要的json数据如下所示: "data" : "my data" 这就是我想到的,但我不明白如何将数据添加到请求并发送,然后解析返回的json数据 string data = "test"; Uri address = new Uri("http://localhost/Service.svc/json"); HttpWebRequest request = (HttpWebRequest)WebRequ
"data" : "my data"
这就是我想到的,但我不明白如何将数据添加到请求并发送,然后解析返回的json数据
string data = "test";
Uri address = new Uri("http://localhost/Service.svc/json");
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(address);
request.Method = "POST";
request.ContentType = "application/json; charset=utf-8";
string postData = "{\"data\":\"" + data + "\"}";
如何将json数据添加到请求中,然后解析响应?使用,来反序列化/解析数据。您可以使用以下方式获取数据:
// corrected to WebRequest from HttpWebRequest
WebRequest request = WebRequest.Create("http://localhost/service.svc/json");
request.Method="POST";
request.ContentType = "application/json; charset=utf-8";
string postData = "{\"data\":\"" + data + "\"}"; //encode your data
//using the javascript serializer
//get a reference to the request-stream, and write the postData to it
using(Stream s = request.GetRequestStream())
{
using(StreamWriter sw = new StreamWriter(s))
sw.Write(postData);
}
//get response-stream, and use a streamReader to read the content
using(Stream s = request.GetResponse().GetResponseStream())
{
using(StreamReader sr = new StreamReader(s))
{
var jsonData = sr.ReadToEnd();
//decode jsonData with javascript serializer
}
}
可能重复: