检查URL是否存在-HTTP请求始终返回异常 [英] Checking if URL exists - HTTP Request always returns an exception

查看:104
本文介绍了检查URL是否存在-HTTP请求始终返回异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

关于如何检查URL是否有效的文章很多.它们全部都具有基本相同的代码,这似乎对每个人都有效-尽管不适用于我,我也不知道为什么.

There are numerous posts on how to check if a URL is valid. All of them feature basically the same code, which seems to work for everyone - not for me though and I don't get why.

    public static bool ifURLexists(string url) 
    {

         try 
         {
              var request = WebRequest.Create(url) as HttpWebRequest;
              request.Method = "HEAD";
              //response ALWAYS throws an exception
              using (var response = (HttpWebResponse)request.GetResponse()) 
              {
                return response.StatusCode == HttpStatusCode.OK;
              }
         }
         catch 
         {
            return false;
         }
    }

我已经使用" http://www.nonexistingwebsiteblabla.com 等参数测试了该方法" http://www.google.com ".无论我插入现有的URL还是不存在的URL,都在此行得到WebException:

I have tested the method with parameters such as "http://www.nonexistingwebsiteblabla.com" and "http://www.google.com". No matter if I insert an existing or a non existing URL, I get a WebException at this line:

    using (var response = (HttpWebResponse)request.GetResponse())

为什么它不起作用?

推荐答案

检查状态 WebException.Status 这将使您知道发生了哪些特定的Web异常.

Check the status WebException.Status This will let you know what specific web exception has occured.

更新:尝试更改request.Method = "HEAD"; 获取并尝试.

Update: Try change the request.Method = "HEAD"; to GET and try.

尝试使用不可用的(404)网址,比较状态. 检查是否有任何内容阻止了您的请求.

Try with a unavailable (404) url, compare the status. Check whether anything is blocking your request.

这是我在代码中进行管理的方式,我仅使用ftp特定状态进行处理."CommStatus"是带有错误代码的ENUM,可在整个应用程序中使用.

This is how i manage in my code, i am handling using only ftp specific status.'CommStatus' is an ENUM with error codes which is available in whole application.

catch (WebException ex)
        {
            FtpWebResponse response = (FtpWebResponse)ex.Response;               
          switch(response.StatusCode)
            {
                case FtpStatusCode.ActionNotTakenFileUnavailable:
                    return CommStatus.PathNotFound; 
                case FtpStatusCode.NotLoggedIn:
                    return CommStatus.AuthenticationError;
                default: return CommStatus.UnhandledException;

            }


        }

下面是可用的WebException状态.

Below are the available Status of WebException.

CacheEntryNotFound
此API支持产品基础结构,不能直接在您的代码中使用.找不到指定的缓存条目.

CacheEntryNotFound
This API supports the product infrastructure and is not intended to be used directly from your code. The specified cache entry was not found.

ConnectFailure
此API支持产品基础结构,不能直接在您的代码中使用.在传输级别无法联系远程服务点.

ConnectFailure
This API supports the product infrastructure and is not intended to be used directly from your code. The remote service point could not be contacted at the transport level.

连接已关闭
此API支持产品基础结构,不能直接在您的代码中使用.连接过早关闭.

ConnectionClosed
This API supports the product infrastructure and is not intended to be used directly from your code. The connection was prematurely closed.

KeepAliveFailure
此API支持产品基础结构,不能直接在您的代码中使用.指定Keep-alive标头的请求的连接意外关闭.

KeepAliveFailure
This API supports the product infrastructure and is not intended to be used directly from your code. The connection for a request that specifies the Keep-alive header was closed unexpectedly.

MessageLengthLimitExceeded
此API支持产品基础结构,不能直接在您的代码中使用.发送请求或从服务器接收响应时,收到超出指定限制的消息.

MessageLengthLimitExceeded
This API supports the product infrastructure and is not intended to be used directly from your code. A message was received that exceeded the specified limit when sending a request or receiving a response from the server.

NameResolutionFailure
此API支持产品基础结构,不能直接在您的代码中使用.名称解析器服务无法解析主机名.

NameResolutionFailure
This API supports the product infrastructure and is not intended to be used directly from your code. The name resolver service could not resolve the host name.

待审核 此API支持产品基础结构,不能直接在您的代码中使用.内部异步请求正在等待处理.

Pending This API supports the product infrastructure and is not intended to be used directly from your code. An internal asynchronous request is pending.

管道失败 此API支持产品基础结构,不能直接在您的代码中使用.该请求是一个固定的请求,在收到响应之前已关闭连接.

PipelineFailure This API supports the product infrastructure and is not intended to be used directly from your code. The request was a piplined request and the connection was closed before the response was received.

ProtocolError
此API支持产品基础结构,不能直接在您的代码中使用.从服务器收到的响应已完成,但指示协议级别的错误.例如,HTTP协议错误(例如401 Access Denied)将使用此状态.

ProtocolError
This API supports the product infrastructure and is not intended to be used directly from your code. The response received from the server was complete but indicated a protocol-level error. For example, an HTTP protocol error such as 401 Access Denied would use this status.

ProxyNameResolutionFailure
此API支持产品基础结构,不能直接在您的代码中使用.名称解析器服务无法解析代理主机名.

ProxyNameResolutionFailure
This API supports the product infrastructure and is not intended to be used directly from your code. The name resolver service could not resolve the proxy host name.

接收失败
此API支持产品基础结构,不能直接在您的代码中使用.没有从远程服务器收到完整的响应.

ReceiveFailure
This API supports the product infrastructure and is not intended to be used directly from your code. A complete response was not received from the remote server.

RequestCanceled 此API支持产品基础结构,不能直接在您的代码中使用.该请求被取消,调用了WebRequest.Abort方法,或者发生了无法分类的错误.这是状态"的默认值.

RequestCanceled This API supports the product infrastructure and is not intended to be used directly from your code. The request was canceled, the WebRequest.Abort method was called, or an unclassifiable error occurred. This is the default value for Status.

RequestProhibitedByCachePolicy
此API支持产品基础结构,不能直接在您的代码中使用.缓存策略不允许该请求.通常,当请求不可缓存并且有效策略禁止将请求发送到服务器时,会发生这种情况.如果请求方法暗示存在请求主体,请求方法需要与服务器直接交互或者请求包含条件标头,则您可能会收到此状态.

RequestProhibitedByCachePolicy
This API supports the product infrastructure and is not intended to be used directly from your code. The request was not permitted by the cache policy. In general, this occurs when a request is not cacheable and the effective policy prohibits sending the request to the server. You might receive this status if a request method implies the presence of a request body, a request method requires direct interaction with the server, or a request contains a conditional header.

RequestProhibitedByProxy
此API支持产品基础结构,不能直接在您的代码中使用.代理不允许此请求.

RequestProhibitedByProxy
This API supports the product infrastructure and is not intended to be used directly from your code. This request was not permitted by the proxy.

SecureChannelFailure
此API支持产品基础结构,不能直接在您的代码中使用.使用SSL建立连接时发生错误.

SecureChannelFailure
This API supports the product infrastructure and is not intended to be used directly from your code. An error occurred while establishing a connection using SSL.

发送失败 此API支持产品基础结构,不能直接在您的代码中使用.无法将完整的请求发送到远程服务器.

SendFailure This API supports the product infrastructure and is not intended to be used directly from your code. A complete request could not be sent to the remote server.

ServerProtocolViolation 此API支持产品基础结构,不能直接在您的代码中使用.服务器响应不是有效的HTTP响应.

ServerProtocolViolation This API supports the product infrastructure and is not intended to be used directly from your code. The server response was not a valid HTTP response.

成功 此API支持产品基础结构,不能直接在您的代码中使用.没有遇到错误.

Success This API supports the product infrastructure and is not intended to be used directly from your code. No error was encountered.

超时 此API支持产品基础结构,不能直接在您的代码中使用.在请求的超时时间内未收到任何响应.

Timeout This API supports the product infrastructure and is not intended to be used directly from your code. No response was received during the time-out period for a request.

TrustFailure
此API支持产品基础结构,不能直接在您的代码中使用.服务器证书无法验证.

TrustFailure
This API supports the product infrastructure and is not intended to be used directly from your code. A server certificate could not be validated.

UnknownError
此API支持产品基础结构,不能直接在您的代码中使用.发生未知类型的异常.

UnknownError
This API supports the product infrastructure and is not intended to be used directly from your code. An exception of unknown type has occurred.

此处有更多详细信息: https://msdn.microsoft.com/zh-CN/library/system.net.webexceptionstatus(v=vs.110).aspx

More details here: https://msdn.microsoft.com/en-us/library/system.net.webexceptionstatus(v=vs.110).aspx

这篇关于检查URL是否存在-HTTP请求始终返回异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆