2011-11-20 25 views
5

Come passare un payload JSON per il consumo di un servizio REST.carico utile JSON per HttpClient in C#?

Ecco che cosa sto provando:

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

Come faccio a passare qualcosa di simile a questo come un parametro per la richiesta ?:

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

risposta

0

Come richiesta HTTP GET rigorosamente non lo faccio pensate di poter postare quel JSON così com'è - avreste bisogno di codificarlo tramite URL e passarlo come argomenti della stringa di query.

Ciò che è possibile fare è inviare a JSON il corpo del contenuto di una richiesta POST tramite WebRequest/WebClient.

È possibile modificare questo esempio di codice da MSDN per inviare il payload JSON come una stringa e che dovrebbe fare il trucco:

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

+0

E il client.Post? Ho modificato il mio codice per quello. – TruMan1

2

Ecco una risposta simile che mostra come pubblicare JSON non elaborato:

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!\"}")); 
} 
Problemi correlati