WebClient
Zakładam użyć WebClient
ponieważ jego łatwego WebRequest-to-ciąg manipulacji. Niestety, WebClient
nie ujawnia kodu odpowiedzi HTTP. Można też założyć, że reakcja była pozytywna (2xx
), chyba że masz exception and read it:
try
{
string content = webClient.DownloadString(url);
}
catch (WebException e)
{
HttpWebResponse response = (System.Net.HttpWebResponse)we.Response;
var statusCode = response.StatusCode;
}
lub jeśli jesteś naprawdę zainteresowany w kodzie sukces można wykorzystać odbicie jak wyjaśniono here.
HttpClient
Można również użyć HttpClient
jeśli jesteś na .NET 4.5, który ma odsłonić kod odpowiedzi, as explained here:
using (HttpClient client = new HttpClient())
{
HttpResponseMessage response = await client.GetAsync(url);
string content = await response.Content.ReadAsStringAsync();
var statusCode = response.StatusCode;
}
HttpWebRequest
Alternatywnie, można po prostu użyć HttpWebRequest
aby uzyskać jego status i odpowiedź as explained here:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "GET";
var response = (HttpWebResponse)request.GetResponse();
using (Stream stream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(stream);
string content = reader.ReadToEnd();
var statusCode = response.StatusCode;
}
huh? używasz GET, więc dostajesz GET. gdzie jest pytanie? –
'request.GetResponse()' otrzymuje obie. To ty bierzesz od niego tylko "StatusCode". – Tobberoth