Handling HTTP response codes in GetStringAsync

I am very new to C #, not to mention developing Windows Phone :)

I try to send a request, get a JSON response, but if there is an error (for example, 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 that this should be something that I am doing wrong in the way I submit the request and save the answer ... but I'm just not sure what.

If there is an error, I get the general: net_http_message_not_success_statuscode

Thank!

+6
source share
3 answers

Instead of using HttpClient, use simple, good 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;

    }
+2
source

You can use the te method of GetAsync () instead of 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();

, HttpStatusCode, .

+18

, -.. . .

0
source

All Articles