处理GetStringAsync中的http响应代码

时间:2014-11-22 15:46:28

标签: c# windows-phone-8.1

我是C#的新手,更不用说Windows Phone开发了:)

我试图发送请求,获取JSON响应,但是如果有错误(例如401),则能够告诉用户这样的。这是我的代码:

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;

        }

我知道这一定是我发送请求和存储响应的方式我做错了但是我不确定是什么。

如果有错误,我会得到一个将军: net_http_message_not_success_statuscode

谢谢!

2 个答案:

答案 0 :(得分:18)

您可以使用te GetAsync()方法而不是GetStringAsync()。

convert -size 127x67 xc:green output.jpg

这样您可以使用可枚举的HttpStatusCode来检查返回的状态代码。

答案 1 :(得分:2)

而不是使用HttpClient使用简单的旧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;

    }