2011-11-20 46 views
5

如何傳遞JSON負載以消耗REST服務。C#中HttpClient的JSON負載?

這裏就是我想:

var requestUrl = "http://example.org"; 

using (var client = new HttpClient()) 
{ 
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualifiedHeaderValue("application/json")); 
    var result = client.Post(requestUrl); 

    var content = result.Content.ReadAsString(); 
    dynamic value = JsonValue.Parse(content); 

    string msg = String.Format("{0} {1}", value.SomeTest, value.AnotherTest); 

    return msg; 
} 

如何傳遞這樣的事情作爲一個參數的要求?:

{"SomeProp1":"abc","AnotherProp1":"123","NextProp2":"zyx"} 

回答

0

作爲一個嚴格的HTTP GET請求我不要認爲你可以按原樣發佈該JSON - 你需要對它進行URL編碼並將其作爲查詢字符串參數傳遞。

你可以做的是通過WebRequest/WebClient發送該JSON POST請求的內容正文。

您可以從MSDN修改此代碼示例發送您的JSON有效載荷爲一個字符串,應該做的伎倆:

http://msdn.microsoft.com/en-us/library/debx8sh9.aspx

+0

client.Post怎麼樣?我修改了我的代碼。 – TruMan1

2

下面是一個類似的答案,顯示如何發佈原始JSON:

Json Format data from console application to service stack

const string RemoteUrl = "http://www.servicestack.net/ServiceStack.Hello/servicestack/hello"; 

var httpReq = (HttpWebRequest)WebRequest.Create(RemoteUrl); 
httpReq.Method = "POST"; 
httpReq.ContentType = httpReq.Accept = "application/json"; 

using (var stream = httpReq.GetRequestStream()) 
using (var sw = new StreamWriter(stream)) 
{ 
    sw.Write("{\"Name\":\"World!\"}"); 
} 

using (var response = httpReq.GetResponse()) 
using (var stream = response.GetResponseStream()) 
using (var reader = new StreamReader(stream)) 
{ 
    Assert.That(reader.ReadToEnd(), Is.EqualTo("{\"Result\":\"Hello, World!\"}")); 
}