Handling http response codes in GetStringAsync
c#, windows-phone-8.1
Solution
Instead of using an HttpClient use a plain good old HttpWebRequest :)
async Task<string> AccessTheWebAsync()
{
HttpWebRequest req = WebRequest.CreateHttp("http://example.com/nodocument.html");
req.Method = "GET";
req.Timeout = 10000;
req.KeepAlive = true;
string content = null;
HttpStatusCode code = HttpStatusCode.OK;
try
{
using (HttpWebResponse response = (HttpWebResponse)await req.GetResponseAsync())
{
using (StreamReader sr = new StreamReader(response.GetResponseStream()))
content = await sr.ReadToEndAsync();
code = response.StatusCode;
}
}
catch (WebException ex)
{
using (HttpWebResponse response = (HttpWebResponse)ex.Response)
{
using (StreamReader sr = new StreamReader(response.GetResponseStream()))
content = sr.ReadToEnd();
code = response.StatusCode;
}
}
//Here you have now content and code.
return content;
}
Problem
i'm very new to C#, let alone Windows Phone development :) I'm trying to send a request, get the JSON response, but if there is an error (such as 401), be able to tell the user such. Here is my code: ``` async Task<string> AccessTheWebAsync() { //builds the credentials for the web request var credentials = new NetworkCredential(globalvars.username, globalvars.password); var handler = new HttpClientHandler { Credentials = credentials }; //calls the web request, stores and returns JSON content HttpClient client = new HttpClient(handler); Task<string> getStringTask = client.GetStringAsync("https://www.bla.com/content"); String urlContents = await getStringTask; return urlContents; } ``` I know it must be something I'm doing wrong in the way that I send the request and store the response...but i'm just not sure what. If there is an error, I get a general: net_http_message_not_success_statuscode Thank you!