Come leggere una risposta WebClient dopo aver pubblicato i dati?
Domanda
Ecco il codice:
using (var client = new WebClient())
{
using (var stream = client.OpenWrite("http://localhost/", "POST"))
{
stream.Write(post, 0, post.Length);
}
}
Ora, come posso leggere l'output HTTP?
Soluzione
Sembra che tu abbia un byte []
di dati da pubblicare; nel qual caso mi aspetto che troverai più facile da usare:
byte[] response = client.UploadData(address, post);
E se la risposta è un testo, qualcosa del tipo:
string s = client.Encoding.GetString(response);
(o la tua scelta di Encoding
- forse Encoding.UTF8
)
Altri suggerimenti
Se si desidera mantenere i flussi ovunque ed evitare di allocare enormi matrici di byte, il che è una buona pratica (ad esempio, se si prevede di pubblicare file di grandi dimensioni), è ancora possibile farlo con una versione derivata di WebClient. Ecco un codice di esempio che lo fa.
using (var client = new WebClientWithResponse())
{
using (var stream = client.OpenWrite(myUrl))
{
// open a huge local file and send it
using (var file = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
file.CopyTo(stream);
}
}
// get response as an array of bytes. You'll need some encoding to convert to string, etc.
var bytes = client.Response;
}
Ed ecco il WebClient personalizzato:
public class WebClientWithResponse : WebClient
{
// we will store the response here. We could store it elsewhere if needed.
// This presumes the response is not a huge array...
public byte[] Response { get; private set; }
protected override WebResponse GetWebResponse(WebRequest request)
{
var response = base.GetWebResponse(request);
var httpResponse = response as HttpWebResponse;
if (httpResponse != null)
{
using (var stream = httpResponse.GetResponseStream())
{
using (var ms = new MemoryStream())
{
stream.CopyTo(ms);
Response = ms.ToArray();
}
}
}
return response;
}
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow