HttpClient无法访问简单的网站

编程入门 行业动态 更新时间:2024-10-15 20:23:53
本文介绍了HttpClient无法访问简单的网站的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

这是我的代码

internal static void ValidateUrl(string url) { Uri validUri; if(Uri.TryCreate(url,UriKind.Absolute,out validUri)) { using (HttpClient client = new HttpClient()) { try { HttpResponseMessage response = client.Get(url); response.EnsureStatusIsSuccessful(); } catch (Exception ex) { //exception handler goes here } } } }

运行此代码时会生成此结果。

This code when i run it produces this result.

ProxyAuthenticationRequired (407) is not one of the following: OK (200), Created (201), Accepted (202), NonAuthoritativeInformation (203), NoContent (204), ResetContent (205), PartialContent (206).

我想做的就是让这段代码验证一个给定的网站是否正常运行。 任何想法?

All i want to do is make this code validate whether a given website is up and running. Any ideas?

推荐答案

您正在调用EnsureStatusIsSuccessful(),它正确地抱怨请求未成功,因为有一个您和要求身份验证的主机之间的代理服务器。

You are invoking EnsureStatusIsSuccessful() which rightfully complains that the request was not successful because there's a proxy server between you and the host which requires authentication.

如果您使用的是框架4.5,我在下面添加了一个略微增强的版本。

If you are on framework 4.5, I've included a slightly enhanced version below.

internal static async Task<bool> ValidateUrl(string url) { Uri validUri; if(Uri.TryCreate(url,UriKind.Absolute,out validUri)) { var client = new HttpClient(); var response = await client.GetAsync(validUri, HttpCompletionOption.ResponseHeadersRead); return response.IsSuccessStatusCode; } return false; }

更多推荐

HttpClient无法访问简单的网站

本文发布于:2023-11-17 14:30:13,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1610185.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:无法访问   简单   网站   HttpClient

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!