Interface HttpClientInterceptor

All Known Implementing Classes:
LoggingInterceptor

public interface HttpClientInterceptor

HTTP 客戶端攔截器介面

提供請求前、請求後與錯誤發生時的攔截點,支援:

  • 日誌記錄
  • 效能監控
  • 安全稽核
  • 請求/回應修改

執行順序

beforeRequest → [HTTP 請求執行] → afterResponse
                     ↓ (錯誤)
                 onError

攔截器鏈 多個攔截器按註冊順序執行:

Interceptor1.beforeRequest()
Interceptor2.beforeRequest()
[HTTP 請求]
Interceptor2.afterResponse()
Interceptor1.afterResponse()

使用範例

public class CustomInterceptor implements HttpClientInterceptor {
    @Override
    public void beforeRequest(InterceptorContext context, ClassicHttpRequest request) {
        // 記錄請求資訊
        log.info("Request: {} {}", request.getMethod(), request.getRequestUri());
    }

    @Override
    public void afterResponse(InterceptorContext context, ClassicHttpRequest request,
                              ClassicHttpResponse response) {
        // 記錄回應資訊
        log.info("Response: {}", response.getCode());
    }

    @Override
    public void onError(InterceptorContext context, ClassicHttpRequest request,
                        Throwable error) {
        // 記錄錯誤資訊
        log.error("Error: {}", error.getMessage());
    }
}
See Also:
  • Method Summary

    Modifier and Type
    Method
    Description
    default void
    afterResponse(InterceptorContext context, org.apache.hc.core5.http.ClassicHttpRequest request, org.apache.hc.core5.http.ClassicHttpResponse response)
    請求執行後的攔截點
    default void
    beforeRequest(InterceptorContext context, org.apache.hc.core5.http.ClassicHttpRequest request)
    請求執行前的攔截點
    default void
    onError(InterceptorContext context, org.apache.hc.core5.http.ClassicHttpRequest request, Throwable error)
    錯誤發生時的攔截點
  • Method Details

    • beforeRequest

      default void beforeRequest(InterceptorContext context, org.apache.hc.core5.http.ClassicHttpRequest request)

      請求執行前的攔截點

      在此方法中可以:

      • 記錄請求資訊
      • 修改請求標頭或參數
      • 記錄開始時間(用於計算耗時)
      Parameters:
      context - 攔截器上下文,可用於在不同攔截點之間傳遞資料
      request - HTTP 請求物件
    • afterResponse

      default void afterResponse(InterceptorContext context, org.apache.hc.core5.http.ClassicHttpRequest request, org.apache.hc.core5.http.ClassicHttpResponse response)

      請求執行後的攔截點

      在此方法中可以:

      • 記錄回應資訊
      • 計算請求耗時
      • 檢查回應狀態
      Parameters:
      context - 攔截器上下文
      request - HTTP 請求物件
      response - HTTP 回應物件
    • onError

      default void onError(InterceptorContext context, org.apache.hc.core5.http.ClassicHttpRequest request, Throwable error)

      錯誤發生時的攔截點

      在此方法中可以:

      • 記錄錯誤資訊
      • 記錄 Stack Trace
      • 觸發告警通知

      注意:此方法不應該拋出異常,否則會覆蓋原始錯誤

      Parameters:
      context - 攔截器上下文
      request - HTTP 請求物件
      error - 發生的錯誤