Asp.net

從 asp.net C# 呼叫外部 json webservice

  • May 29, 2012

我需要從 C# Asp.net 呼叫 json webservice。服務返回一個 json 對象,webservice 想要的 json 數據如下所示:

"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 數據添加到我的請求中,然後解析響應?

使用JavaScriptSerializer來反序列化/解析數據。您可以使用以下方法獲取數據:

// 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
   }
}

引用自:https://stackoverflow.com/questions/2071097