Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling http response codes in GetStringAsync

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!

like image 901
Brendon Avatar asked Nov 22 '14 15:11

Brendon


2 Answers

You could use te GetAsync() method instead of the GetStringAsync().

HttpResponseMessage response = await client.GetAsync("https://www.bla.com/content");

if(!response.IsSuccessStatusCode)
{
     if (response.StatusCode == HttpStatusCode.Unauthorized)
     {
         do something...
     }
}
String urlContents = await response.Content.ReadAsStringAsync();

This way you can make use of the HttpStatusCode enumerable to check the returned status code.

like image 134
user3576450 Avatar answered Nov 07 '22 21:11

user3576450


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;

    }
like image 21
Gusman Avatar answered Nov 07 '22 20:11

Gusman