2013-04-10 19 views
85

Sto cercando di ottenere il contenuto di HttpResponseMessage. Dovrebbe essere: {"message":"Action '' does not exist!","success":false}, ma non so come estrarlo da HttpResponseMessage.Come ricevere contenuto/messaggio da HttpResponseMessage

HttpClient httpClient = new HttpClient(); 
HttpResponseMessage response = await httpClient.GetAsync("http://****?action="); 
txtBlock.Text = Convert.ToString(response); //wrong! 

In questo caso txtBlock avrebbe valore:

StatusCode: 200, ReasonPhrase: 'OK', Version: 1.1, Content: System.Net.Http.StreamContent, Headers: 
{ 
    Vary: Accept-Encoding 
    Keep-Alive: timeout=15, max=100 
    Connection: Keep-Alive 
    Date: Wed, 10 Apr 2013 20:46:37 GMT 
    Server: Apache/2.2.16 
    Server: (Debian) 
    X-Powered-By: PHP/5.3.3-7+squeeze14 
    Content-Length: 55 
    Content-Type: text/html 
} 

risposta

38

È necessario chiamare GetResponse().

Stream receiveStream = response.GetResponseStream(); 
StreamReader readStream = new StreamReader (receiveStream, Encoding.UTF8); 
txtBlock.Text = readStream.ReadToEnd(); 
+15

Grazie, ma perché ottengo questo errore qui: "System.Net.Http.HttpResponseMessage' non contiene una definizione per 'GetResponseStream' e non è stato trovato alcun metodo di estensione 'GetResponseStream' che accetta un primo argomento di tipo 'System.Net.Http.HttpResponseMessage' " – Clem

+7

@Klemzy - Perché lo si chiama in modo asincrono. Prova invece a utilizzare la proprietà 'Content'. Guarda [esempio qui] (http://msdn.microsoft.com/en-us/library/windows/apps/xaml/hh781239.aspx). Scorri fino al secondo passaggio. – Icemanind

+0

Sì, ma non so come :) Scusa sono principiante in C# – Clem

27

Prova questo, è possibile creare un metodo di estensione in questo modo:

public static string ContentToString(this HttpContent httpContent) 
    { 
     var readAsStringAsync = httpContent.ReadAsStringAsync(); 
     return readAsStringAsync.Result; 
    } 

e poi, semplice chiamata al metodo di estensione:

txtBlock.Text = response.Content.ContentToString(); 

Spero che questo aiuto voi ;-)

+0

Di gran lunga il più semplice da installare – bump

184

Penso che l'approccio più semplice sia solo per modificare l'ultima riga su

txtBlock.Text = await response.Content.ReadAsStringAsync(); //right! 

In questo modo non è necessario introdurre alcun lettore di stream e non è necessario alcun metodo di estensione.

+4

Non sono sicuro del motivo per cui questa non è la risposta accettata, soprattutto perché questo ti dà la possibilità di serializzare facilmente i contenuti nei tuoi oggetti. –

+3

ReadAsStringAsync non gestisce bene gli errori IMHO. – stannius

+4

Puoi anche usare Response.Content.ReadAsStringAsync(). Risultato invece di utilizzare attendere – Justin

0

È possibile utilizzare il metodo GetStringAsync:

var uri = new Uri("http://yoururlhere"); 
var response = await client.GetStringAsync(uri); 
5

Se si vuole lanciare al tipo specifico (ad esempio all'interno di test) è possibile utilizzare ReadAsAsync metodo di estensione:

object yourTypeInstance = await response.Content.ReadAsAsync(typeof(YourType)); 

o in seguito per sincrona codice:

object yourTypeInstance = response.Content.ReadAsAsync(typeof(YourType)).Result; 

Aggiornamento: c'è anche l'opzione generica di ReadAsAsync<> che restituisce specifica istanza del tipo di oggetto invece di dichiarata uno:

YourType yourTypeInstance = await response.Content.ReadAsAsync<YourType>(); 
+2

object yourTypeInstance = attende response.Content.ReadAsAsync (typeof (YourType)); dovrebbe essere var yourTypeInstance = attendere response.Content.ReadAsAsync (); –

Problemi correlati