在GetStringAsync中处理http响应代码

12

我对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。

谢谢!


如果你想要更好的掌控,使用HttpWebRequest。通过它,你可以获取有关错误的所有信息,甚至可以读取错误响应正文。 - Gusman
对不起,您能给我一个例子,说明我应该如何使用它,而不是我上面的代码吗? - Brendon
2个回答

35

你可以使用 GetAsync() 方法来代替 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枚举来检查返回的状态代码。


如果你在同一行代码中使用.Result同步等待结果,那么调用GetAsync的意义何在?已提交编辑。 - Dan Bechard

1

不要使用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;

    }

我确实尝试过,但我现在遇到的问题是GetResponse()在WinPhone上似乎不可用...有getResponseAsync(),但仍在尝试弄清如何使用它... - Brendon
您先生,真是太棒了。非常感谢! - Brendon
1
@Gusman 真的很喜欢它。我已经无法计算我曾经用 GOF HttpWebRequest 替换 HttpClient 的次数了。 - pim
2
不回答 HttpHandler,而是提供了一种与所请求的答案不同的解决方案。 - ShellNinja

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接