HttpClient返回异常分类

当遇到某一类异常不进行重试

Code

var polly = Policy.Handle<Exception>(ex => NeedHandlerRetryException(ex)).WaitAndRetryAsync(2,
                    retryAttempt => TimeSpan.FromSeconds(2)
                 );

private bool NeedHandlerRetryException(Exception ex)
{
    if(ex.StatusCode == 0)
    {
        var actualException = ex.InnerException;
        if(actualException  != null)
        {                
            if(actualException is TimeoutException ||(actualException is WebException webEx && webEx.Statu== WebExceptionStatuNameResolutionFailure)) //连时 || 域名解析失败
            {
                return false;
            }
            if(actualException is SocketException)//网络中断
            {
                return true;
            }
            var retryExceptions = ne WebExceptionStatus[]
            {
                WebExceptionStatuConnectFailure,
                WebExceptionStatuConnectionClosed,
                WebExceptionStatuRequestCanceled
            };
            if (actualException is WebException webException &webException.Status.Is(retryExceptions))//连接失败,是需要其他status?如果不需要,该方法只返回false的场景
            {
                return true;
            }
            
        }
    }
    return true;
}

// 摘要:
//     Defines status codes for the System.NetWebException class.
public enum WebExceptionStatus
{
    //
    // 摘要:
    //     No error was encountered.
    Success = 0,
    //
    // 摘要:
    //     The name resolver service could notresolve the host name.
    NameResolutionFailure = 1,
    //
    // 摘要:
    //     The remote service point could not becontacted at the transport level.
    ConnectFailure = 2,
    //
    // 摘要:
    //     A complete response was not receivedfrom the remote server.
    ReceiveFailure = 3,
    //
    // 摘要:
    //     A complete request could not be sent tothe remote server.
    SendFailure = 4,
    //
    // 摘要:
    //     The request was a pipelined request andthe connection was closed before the
    //     response was received.
    PipelineFailure = 5,
    //
    // 摘要:
    //     The request was canceled, the SystemNet.WebRequest.Abort method was called,
    //     or an unclassifiable error occurred.This is the default value for System.NetWebException.Status.
    RequestCanceled = 6,
    //
    // 摘要:
    //     The response received from the serverwas complete but indicated a protocol-level
    //     error. For example, an HTTP protocolerror such as 401 Access Denied would use
    //     this status.
    ProtocolError = 7,
    //
    // 摘要:
    //     The connection was prematurely closed.
    ConnectionClosed = 8,
    //
    // 摘要:
    //     A server certificate could not bevalidated.
    TrustFailure = 9,
    //
    // 摘要:
    //     An error occurred while establishing aconnection using SSL.
    SecureChannelFailure = 10,
    //
    // 摘要:
    //     The server response was not a validHTTP response.
    ServerProtocolViolation = 11,
    //
    // 摘要:
    //     The connection for a request thatspecifies the Keep-alive header was closed
    //     unexpectedly.
    KeepAliveFailure = 12,
    //
    // 摘要:
    //     An internal asynchronous request ispending.
    Pending = 13,
    //
    // 摘要:
    //     No response was received during thetime-out period for a request.
    Timeout = 14,
    //
    // 摘要:
    //     The name resolver service could notresolve the proxy host name.
    ProxyNameResolutionFailure = 15,
    //
    // 摘要:
    //     An exception of unknown type hasoccurred.
    UnknownError = 16,
    //
    // 摘要:
    //     A message was received that exceededthe specified limit when sending a request
    //     or receiving a response from the server.
    MessageLengthLimitExceeded = 17,
    //
    // 摘要:
    //     The specified cache entry was not found.
    CacheEntryNotFound = 18,
    //
    // 摘要:
    //     The request was not permitted by thecache policy. In general, this occurs when
    //     a request is not cacheable and theeffective policy prohibits sending the request
    //     to the server. You might receive thisstatus if a request method implies the
    //     presence of a request body, a requestmethod requires direct interaction with
    //     the server, or a request contains aconditional header.
    RequestProhibitedByCachePolicy = 19,
    //
    // 摘要:
    //     This request was not permitted by theproxy.
    RequestProhibitedByProxy = 20
}

参考地址

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
HttpClient 是一个Java中处理Http请求的开源框架,它可以发送Http请求并接收响应。当HttpClient向服务器发出请求时,服务器将响应返回HttpClientHttpClient将响应解析并返回给调用者。 HttpClient返回值通常是一个 HttpResponse 对象,该对象包含了服务器响应的所有信息,例如响应状态码、响应头部和响应正文等。开发人员可以通过该对象来获取服务器响应的各种信息,并做出相应的处理。 以下是一个简单的示例,展示了如何使用 HttpClient 发送一个 GET 请求,并获取服务器响应的状态码和响应正文: ```java import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; public class HttpClientDemo { public static void main(String[] args) throws Exception { // 创建HttpClient对象 CloseableHttpClient httpClient = HttpClients.createDefault(); // 创建HttpGet对象,设置请求URL HttpGet httpGet = new HttpGet("http://www.example.com"); // 发送GET请求,获取响应对象 CloseableHttpResponse response = httpClient.execute(httpGet); try { // 获取响应状态码 int statusCode = response.getStatusLine().getStatusCode(); System.out.println("Status Code: " + statusCode); // 获取响应正文 String responseBody = EntityUtils.toString(response.getEntity(), "UTF-8"); System.out.println("Response Body: " + responseBody); } finally { // 关闭响应对象 response.close(); } } } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值