使用HTTP全局拦截器 (C/C++)
===================

#### 场景介绍

从API version 24开始，通过HTTP全局拦截器（包含只读拦截器和可修改拦截器），开发者可以在只读拦截器中监控HTTP流量，实现日志记录功能，也可以在可修改拦截器中添加自定义逻辑，实现修改请求头、修改响应头、修改响应体等功能。

#### 接口说明

HTTP全局拦截器常用接口如下表所示，详细的接口说明请参考[http\_interceptor.h](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/capi-net-http-interceptor-h)。

| 接口名 | 描述 |
| :-- | :-- |
| OH\_Http\_AddReadOnlyInterceptor(struct OH\_Http\_Interceptor \*interceptor) | 添加一个HTTP全局只读拦截器。 |
| OH\_Http\_AddWritableInterceptor(struct OH\_Http\_Interceptor \*interceptor) | 添加一个HTTP全局可修改拦截器。 |
| OH\_Http\_RemoveInterceptor(struct OH\_Http\_Interceptor \*interceptor) | 删除指定的HTTP全局拦截器。 |
| OH\_Http\_RemoveAllInterceptors(int32\_t groupId) | 删除指定组ID的所有HTTP全局拦截器。 |
| OH\_Http\_StartAllInterceptors(int32\_t groupId) | 启用指定组ID的所有HTTP全局拦截器。 |
| OH\_Http\_StopAllInterceptors(int32\_t groupId) | 停用指定组ID的所有HTTP全局拦截器。 |

#### 开发步骤

使用本文档涉及接口创建并使用HTTP全局拦截器时，需先创建Native C++工程，在源文件中封装相关接口，然后在ArkTS层调用封装好的接口，使用hilog或console.info等方法将日志打印到控制台或生成设备日志。

本文以添加HTTP全局只读响应拦截器、可修改请求拦截器、可修改响应拦截器为例，提供具体的开发指导。

#### \[h2\]添加开发依赖

**添加动态链接库**

CMakeLists.txt中添加以下lib:

libace\_napi.z.so
libhttp\_interceptor.so

**头文件**

#include "napi/native\_api.h"
#include "network/netstack/http\_interceptor.h"
#include "network/netstack/http\_interceptor\_type.h"

#### \[h2\]构建工程

1.  在源文件中编写调用该API的代码，实现HTTP全局拦截器的处理函数和相关操作。
    
    #include "napi/native\_api.h"
    #include "network/netstack/http\_interceptor.h"
    #include "network/netstack/http\_interceptor\_type.h"
    #include "hilog/log.h"
    
    #include <cstring>
    #include <cstdlib>
    #include <string>
    
    #undef LOG\_DOMAIN
    #undef LOG\_TAG
    #define LOG\_DOMAIN 0x3200 // 全局domain宏，标识业务领域
    #define LOG\_TAG "HttpInterceptorDemo"  // 全局tag宏，标识模块日志tag
    
    // 全局只读响应拦截器实例
    static OH\_Http\_Interceptor g\_readOnlyResponseInterceptor = {
        .groupId = 1,
        .stage = OH\_STAGE\_RESPONSE,
        .type = OH\_TYPE\_READ\_ONLY,
        .enabled = 1,
        .handler = nullptr,
    };
    
    // 可修改请求拦截器实例（用于修改Network Kit的请求数据包）
    static OH\_Http\_Interceptor g\_modifyRequestInterceptor = {
        .groupId = 2,
        .stage = OH\_STAGE\_REQUEST,
        .type = OH\_TYPE\_MODIFY\_NETWORK\_KIT,
        .enabled = 1,
        .handler = nullptr,
    };
    
    // 可修改响应拦截器实例（用于修改Network Kit的响应数据包）
    static OH\_Http\_Interceptor g\_modifyResponseInterceptor = {
        .groupId = 3,
        .stage = OH\_STAGE\_RESPONSE,
        .type = OH\_TYPE\_MODIFY\_NETWORK\_KIT,
        .enabled = 1,
        .handler = nullptr,
    };
    
    // 内存分配和字符串拷贝辅助函数
    char \*MallocCString(const std::string &origin)
    {
        if (origin.empty()) {
            return nullptr;
        }
    
        auto len = origin.length() + 1;
        char \*res = static\_cast<char \*>(malloc(sizeof(char) \* len));
        if (res == nullptr) {
            return nullptr;
        }
        return std::char\_traits<char>::copy(res, origin.c\_str(), len);
    }
    
    // 日志打印辅助函数
    void LogHeader(OH\_Http\_Interceptor\_Headers \*headers)
    {
        OH\_LOG\_INFO(LOG\_APP, "---------------------header begin---------------------");
        while (headers != nullptr) {
            if (headers->data != nullptr) {
                OH\_LOG\_INFO(LOG\_APP, "%{public}s", headers->data);
            }
            headers = headers->next;
        }
        OH\_LOG\_INFO(LOG\_APP, "---------------------header end---------------------");
    }
    
    // 打印响应信息
    void PrintResponseInfo(OH\_Http\_Interceptor\_Response \*response)
    {
        OH\_LOG\_INFO(LOG\_APP, "-----PrintResponseInfo Begin-----");
        if (response != nullptr) {
            OH\_LOG\_INFO(LOG\_APP, "responseCode = %{public}d", response->responseCode);
            if (response->body.buffer != nullptr) {
                OH\_LOG\_INFO(LOG\_APP, "body = %{public}s", response->body.buffer);
            }
            if (response->headers != nullptr) {
                LogHeader(response->headers);
            }
    
            OH\_LOG\_INFO(LOG\_APP, "dns: %{public}lf", response->performanceTiming.dnsTiming);
            OH\_LOG\_INFO(LOG\_APP, "tcp: %{public}lf", response->performanceTiming.tcpTiming);
            OH\_LOG\_INFO(LOG\_APP, "tls: %{public}lf", response->performanceTiming.tlsTiming);
            OH\_LOG\_INFO(LOG\_APP, "snd: %{public}lf", response->performanceTiming.firstSendTiming);
            OH\_LOG\_INFO(LOG\_APP, "rcv: %{public}lf", response->performanceTiming.firstReceiveTiming);
            OH\_LOG\_INFO(LOG\_APP, "tot: %{public}lf", response->performanceTiming.totalFinishTiming);
            OH\_LOG\_INFO(LOG\_APP, "rdr: %{public}lf", response->performanceTiming.redirectTiming);
            OH\_LOG\_INFO(LOG\_APP, "-----PrintResponseInfo End-----");
        }
    }
    
    // 只读响应拦截器处理函数
    OH\_Interceptor\_Result ReadOnlyResponseInterceptorHandler(
        OH\_Http\_Interceptor\_Request \*request,
        OH\_Http\_Interceptor\_Response \*response,
        int32\_t \*isModified)
    {
        (void)request;
        (void)isModified;
        
        if (response != nullptr) {
            OH\_LOG\_INFO(LOG\_APP, "---ReadOnly Response Interceptor Handler---");
            PrintResponseInfo(response);
        }
        return OH\_CONTINUE;
    }
    
    // 修改请求方法
    static void ModifyRequestMethod(OH\_Http\_Interceptor\_Request \*request)
    {
        if (request->method.buffer != nullptr) {
            // 释放原有内存，必须使用free释放由malloc分配的内存
            free((void \*)request->method.buffer);
            
            // 重新申请内存并设置新值，必须使用malloc分配内存
            const std::string newMethodStr = "GET";
            char \*newMethodBuffer = MallocCString(newMethodStr);
            if (newMethodBuffer != nullptr) {
                request->method.buffer = newMethodBuffer;
                request->method.length = newMethodStr.length();
                OH\_LOG\_INFO(LOG\_APP, "Modified Method: %{public}s", request->method.buffer);
            }
        }
    }
    
    // 修改第一个header节点
    static void ModifyFirstHeaderNode(OH\_Http\_Interceptor\_Headers \*\*headers, const char \*headerData)
    {
        size\_t headerLen = strlen(headerData) + 1;
        
        if (\*headers != nullptr) {
            // 修改第一个header节点
            if ((\*headers)->data != nullptr) {
                // 释放原有内存，必须使用free释放由malloc分配的内存
                free((void \*)(\*headers)->data);
            }
            // 必须使用malloc分配内存
            const std::string headerDataStr = headerData;
            char \*headerBuffer = MallocCString(headerDataStr);
            if (headerBuffer != nullptr) {
                (\*headers)->data = headerBuffer;
                OH\_LOG\_INFO(LOG\_APP, "Modified first header: %{public}s", headerData);
            }
        } else {
            // 若没有header节点，创建新的第一个节点
            // 创建新的header节点，必须使用malloc分配内存
            OH\_Http\_Interceptor\_Headers \*newHeader =
                (OH\_Http\_Interceptor\_Headers \*)malloc(sizeof(OH\_Http\_Interceptor\_Headers));
            if (newHeader != nullptr) {
                // 必须使用malloc分配内存
                const std::string headerDataStr = headerData;
                char \*headerBuffer = MallocCString(headerDataStr);
                if (headerBuffer != nullptr) {
                    newHeader->data = headerBuffer;
                    newHeader->next = nullptr;
                    \*headers = newHeader;
                    OH\_LOG\_INFO(LOG\_APP, "Created first header: %{public}s", headerData);
                } else {
                    // 内存分配失败，释放header节点，必须使用free释放由malloc分配的内存
                    free((void \*)newHeader);
                }
            }
        }
    }
    
    // 修改body内容
    static void ModifyBodyContent(Http\_Buffer \*body, const char \*newBodyContent)
    {
        // 释放原有body内存，必须使用free释放由malloc分配的内存
        if (body->buffer != nullptr) {
            free((void \*)body->buffer);
        }
        
        // 重新申请内存并设置新的body内容，必须使用malloc分配内存
        const std::string bodyContentStr = newBodyContent;
        char \*bodyBuffer = MallocCString(bodyContentStr);
        if (bodyBuffer != nullptr) {
            body->buffer = bodyBuffer;
            body->length = bodyContentStr.length();
            OH\_LOG\_INFO(LOG\_APP, "Modified Body: %{public}s", body->buffer);
        }
    }
    
    // 可修改请求拦截器处理函数（修改Network Kit的请求数据包）
    OH\_Interceptor\_Result ModifyRequestInterceptorHandler(
        OH\_Http\_Interceptor\_Request \*request,
        OH\_Http\_Interceptor\_Response \*response,
        int32\_t \*isModified)
    {
        (void)response;
        
        if (request != nullptr) {
            OH\_LOG\_INFO(LOG\_APP, "---Modify Interceptor Handler---");
            OH\_LOG\_INFO(LOG\_APP, "Original URL: %{public}s", request->url.buffer);
            OH\_LOG\_INFO(LOG\_APP, "Original Method: %{public}s", request->method.buffer);
            
            // 修改请求方法
            ModifyRequestMethod(request);
            
            // 修改第一个请求头
            const char \*requestHeaderData = "X-Custom-Header: CustomValue";
            ModifyFirstHeaderNode(&request->headers, requestHeaderData);
            
            // 修改请求体
            const char \*requestBodyData = "{\\"key\\": \\"value\\"}";
            ModifyBodyContent(&request->body, requestBodyData);
            
            // 标记为已修改
            \*isModified = 1;
            OH\_LOG\_INFO(LOG\_APP, "Request modified: %{public}d", \*isModified);
        }
        
        // 返回OH\_CONTINUE表示继续处理请求
        // 返回OH\_ABORT表示中止请求，请求将不会发送到服务器
        return OH\_CONTINUE;
    }
    
    // 可修改响应拦截器处理函数（修改Network Kit的响应数据包）
    OH\_Interceptor\_Result ModifyResponseInterceptorHandler(
        OH\_Http\_Interceptor\_Request \*request,
        OH\_Http\_Interceptor\_Response \*response,
        int32\_t \*isModified)
    {
        (void)request;
        
        if (response != nullptr) {
            OH\_LOG\_INFO(LOG\_APP, "---Modify Response Interceptor Handler---");
            OH\_LOG\_INFO(LOG\_APP, "Original Response Code: %{public}d", response->responseCode);
            if (response->body.buffer != nullptr) {
                OH\_LOG\_INFO(LOG\_APP, "Original Response Body: %{public}s", response->body.buffer);
            }
            
            // 修改响应体
            const char \*responseBodyData = "{\\"modified\\": true, \\"message\\": \\"Response modified by interceptor\\"}";
            ModifyBodyContent(&response->body, responseBodyData);
            
            // 修改第一个响应头
            const char \*responseHeaderData = "X-Intercepted: true";
            ModifyFirstHeaderNode(&response->headers, responseHeaderData);
            
            // 标记为已修改
            \*isModified = 1;
            OH\_LOG\_INFO(LOG\_APP, "Response modified: %{public}d", \*isModified);
        }
        
        // 返回OH\_CONTINUE表示继续处理响应
        // 返回OH\_ABORT表示终止当前拦截器链的执行
        return OH\_CONTINUE;
    }
    
    // 添加只读响应拦截器
    static napi\_value AddReadOnlyResponseInterceptor(napi\_env env, napi\_callback\_info info)
    {
        napi\_value result;
        
        // 设置拦截器处理函数
        g\_readOnlyResponseInterceptor.handler = ReadOnlyResponseInterceptorHandler;
        
        // 添加拦截器
        int ret = OH\_Http\_AddReadOnlyInterceptor(&g\_readOnlyResponseInterceptor);
        
        OH\_LOG\_INFO(LOG\_APP, "AddReadOnlyResponseInterceptor ret: %{public}d", ret);
        napi\_create\_int32(env, ret, &result);
        return result;
    }
    
    // 移除只读响应拦截器
    static napi\_value RemoveReadOnlyResponseInterceptor(napi\_env env, napi\_callback\_info info)
    {
        napi\_value result;
        
        // 移除拦截器
        int ret = OH\_Http\_RemoveInterceptor(&g\_readOnlyResponseInterceptor);
        
        OH\_LOG\_INFO(LOG\_APP, "RemoveReadOnlyResponseInterceptor ret: %{public}d", ret);
        napi\_create\_int32(env, ret, &result);
        return result;
    }
    
    // 启用只读响应拦截器组
    static napi\_value StartReadOnlyResponseInterceptors(napi\_env env, napi\_callback\_info info)
    {
        napi\_value result;
        
        // 启用组ID为1的所有拦截器
        int ret = OH\_Http\_StartAllInterceptors(1);
        
        OH\_LOG\_INFO(LOG\_APP, "StartReadOnlyResponseInterceptors ret: %{public}d", ret);
        napi\_create\_int32(env, ret, &result);
        return result;
    }
    
    // 停用只读响应拦截器组
    static napi\_value StopReadOnlyResponseInterceptors(napi\_env env, napi\_callback\_info info)
    {
        napi\_value result;
        
        // 停用组ID为1的所有拦截器
        int ret = OH\_Http\_StopAllInterceptors(1);
        
        OH\_LOG\_INFO(LOG\_APP, "StopReadOnlyResponseInterceptors ret: %{public}d", ret);
        napi\_create\_int32(env, ret, &result);
        return result;
    }
    
    // 删除只读响应拦截器组
    static napi\_value RemoveAllReadOnlyResponseInterceptors(napi\_env env, napi\_callback\_info info)
    {
        napi\_value result;
        
        // 删除组ID为1的所有拦截器
        int ret = OH\_Http\_RemoveAllInterceptors(1);
        
        OH\_LOG\_INFO(LOG\_APP, "RemoveAllReadOnlyResponseInterceptors ret: %{public}d", ret);
        napi\_create\_int32(env, ret, &result);
        return result;
    }
    
    // 添加可修改请求拦截器（OH\_TYPE\_MODIFY\_NETWORK\_KIT类型）
    static napi\_value AddModifyRequestInterceptor(napi\_env env, napi\_callback\_info info)
    {
        napi\_value result;
        
        // 设置拦截器处理函数
        g\_modifyRequestInterceptor.handler = ModifyRequestInterceptorHandler;
        
        // 添加可修改拦截器
        int ret = OH\_Http\_AddWritableInterceptor(&g\_modifyRequestInterceptor);
        
        OH\_LOG\_INFO(LOG\_APP, "AddModifyRequestInterceptor ret: %{public}d", ret);
        napi\_create\_int32(env, ret, &result);
        return result;
    }
    
    // 移除可修改请求拦截器
    static napi\_value RemoveModifyRequestInterceptor(napi\_env env, napi\_callback\_info info)
    {
        napi\_value result;
        
        // 移除拦截器
        int ret = OH\_Http\_RemoveInterceptor(&g\_modifyRequestInterceptor);
        
        OH\_LOG\_INFO(LOG\_APP, "RemoveModifyRequestInterceptor ret: %{public}d", ret);
        napi\_create\_int32(env, ret, &result);
        return result;
    }
    
    // 启用可修改请求拦截器组
    static napi\_value StartModifyRequestInterceptors(napi\_env env, napi\_callback\_info info)
    {
        napi\_value result;
        
        // 启用组ID为2的所有拦截器
        int ret = OH\_Http\_StartAllInterceptors(2);
        
        OH\_LOG\_INFO(LOG\_APP, "StartModifyRequestInterceptors ret: %{public}d", ret);
        napi\_create\_int32(env, ret, &result);
        return result;
    }
    
    // 停用可修改请求拦截器组
    static napi\_value StopModifyRequestInterceptors(napi\_env env, napi\_callback\_info info)
    {
        napi\_value result;
        
        // 停用组ID为2的所有拦截器
        int ret = OH\_Http\_StopAllInterceptors(2);
        
        OH\_LOG\_INFO(LOG\_APP, "StopModifyRequestInterceptors ret: %{public}d", ret);
        napi\_create\_int32(env, ret, &result);
        return result;
    }
    
    // 删除可修改请求拦截器组
    static napi\_value RemoveAllModifyRequestInterceptors(napi\_env env, napi\_callback\_info info)
    {
        napi\_value result;
        
        // 删除组ID为2的所有拦截器
        int ret = OH\_Http\_RemoveAllInterceptors(2);
        
        OH\_LOG\_INFO(LOG\_APP, "RemoveAllModifyRequestInterceptors ret: %{public}d", ret);
        napi\_create\_int32(env, ret, &result);
        return result;
    }
    
    // 添加可修改响应拦截器（OH\_TYPE\_MODIFY\_NETWORK\_KIT类型）
    static napi\_value AddModifyResponseInterceptor(napi\_env env, napi\_callback\_info info)
    {
        napi\_value result;
        
        // 设置拦截器处理函数
        g\_modifyResponseInterceptor.handler = ModifyResponseInterceptorHandler;
        
        // 添加可修改拦截器
        int ret = OH\_Http\_AddWritableInterceptor(&g\_modifyResponseInterceptor);
        
        OH\_LOG\_INFO(LOG\_APP, "AddModifyResponseInterceptor ret: %{public}d", ret);
        napi\_create\_int32(env, ret, &result);
        return result;
    }
    
    // 移除可修改响应拦截器
    static napi\_value RemoveModifyResponseInterceptor(napi\_env env, napi\_callback\_info info)
    {
        napi\_value result;
        
        // 移除拦截器
        int ret = OH\_Http\_RemoveInterceptor(&g\_modifyResponseInterceptor);
        
        OH\_LOG\_INFO(LOG\_APP, "RemoveModifyResponseInterceptor ret: %{public}d", ret);
        napi\_create\_int32(env, ret, &result);
        return result;
    }
    
    // 启用可修改响应拦截器组
    static napi\_value StartModifyResponseInterceptors(napi\_env env, napi\_callback\_info info)
    {
        napi\_value result;
        
        // 启用组ID为3的所有拦截器
        int ret = OH\_Http\_StartAllInterceptors(3);
        
        OH\_LOG\_INFO(LOG\_APP, "StartModifyResponseInterceptors ret: %{public}d", ret);
        napi\_create\_int32(env, ret, &result);
        return result;
    }
    
    // 停用可修改响应拦截器组
    static napi\_value StopModifyResponseInterceptors(napi\_env env, napi\_callback\_info info)
    {
        napi\_value result;
        
        // 停用组ID为3的所有拦截器
        int ret = OH\_Http\_StopAllInterceptors(3);
        
        OH\_LOG\_INFO(LOG\_APP, "StopModifyResponseInterceptors ret: %{public}d", ret);
        napi\_create\_int32(env, ret, &result);
        return result;
    }
    
    // 删除可修改响应拦截器组
    static napi\_value RemoveAllModifyResponseInterceptors(napi\_env env, napi\_callback\_info info)
    {
        napi\_value result;
        
        // 删除组ID为3的所有拦截器
        int ret = OH\_Http\_RemoveAllInterceptors(3);
        
        OH\_LOG\_INFO(LOG\_APP, "RemoveAllModifyResponseInterceptors ret: %{public}d", ret);
        napi\_create\_int32(env, ret, &result);
        return result;
    }
    
    上述代码实现了多种HTTP全局拦截器，包括只读响应拦截器、可修改请求拦截器和可修改响应拦截器。在拦截器处理函数中，会打印请求或响应的相关信息，如状态码、请求体/响应体、请求头/响应头以及性能指标等。
    
2.  初始化并导出通过N-API封装的napi\_value类型对象，通过外部函数接口将函数提供给JavaScript调用。
    
    EXTERN\_C\_START
    static napi\_value Init(napi\_env env, napi\_value exports)
    {
        napi\_property\_descriptor desc\[\] = {
            {"AddReadOnlyResponseInterceptor", nullptr, AddReadOnlyResponseInterceptor, nullptr, nullptr, nullptr,
                napi\_default, nullptr},
            {"RemoveReadOnlyResponseInterceptor", nullptr, RemoveReadOnlyResponseInterceptor, nullptr, nullptr, nullptr,
                napi\_default, nullptr},
            {"StartReadOnlyResponseInterceptors", nullptr, StartReadOnlyResponseInterceptors, nullptr, nullptr, nullptr,
                napi\_default, nullptr},
            {"StopReadOnlyResponseInterceptors", nullptr, StopReadOnlyResponseInterceptors, nullptr, nullptr, nullptr,
                napi\_default, nullptr},
            {"RemoveAllReadOnlyResponseInterceptors", nullptr, RemoveAllReadOnlyResponseInterceptors, nullptr, nullptr,
                nullptr, napi\_default, nullptr},
            {"AddModifyRequestInterceptor", nullptr, AddModifyRequestInterceptor, nullptr, nullptr, nullptr,
                napi\_default, nullptr},
            {"RemoveModifyRequestInterceptor", nullptr, RemoveModifyRequestInterceptor, nullptr, nullptr, nullptr,
                napi\_default, nullptr},
            {"StartModifyRequestInterceptors", nullptr, StartModifyRequestInterceptors, nullptr, nullptr, nullptr,
                napi\_default, nullptr},
            {"StopModifyRequestInterceptors", nullptr, StopModifyRequestInterceptors, nullptr, nullptr, nullptr,
                napi\_default, nullptr},
            {"RemoveAllModifyRequestInterceptors", nullptr, RemoveAllModifyRequestInterceptors, nullptr, nullptr, nullptr,
                napi\_default, nullptr},
            {"AddModifyResponseInterceptor", nullptr, AddModifyResponseInterceptor, nullptr, nullptr, nullptr,
                napi\_default, nullptr},
            {"RemoveModifyResponseInterceptor", nullptr, RemoveModifyResponseInterceptor, nullptr, nullptr, nullptr,
                napi\_default, nullptr},
            {"StartModifyResponseInterceptors", nullptr, StartModifyResponseInterceptors, nullptr, nullptr, nullptr,
                napi\_default, nullptr},
            {"StopModifyResponseInterceptors", nullptr, StopModifyResponseInterceptors, nullptr, nullptr, nullptr,
                napi\_default, nullptr},
            {"RemoveAllModifyResponseInterceptors", nullptr, RemoveAllModifyResponseInterceptors, nullptr, nullptr,
                nullptr, napi\_default, nullptr},
        };
        napi\_define\_properties(env, exports, sizeof(desc) / sizeof(desc\[0\]), desc);
        return exports;
    }
    EXTERN\_C\_END
    
3.  将上一步中初始化成功的对象通过RegisterEntryModule函数，使用napi\_module\_register函数将模块注册到Node.js中。
    
    static napi\_module demoModule = {
        .nm\_version = 1,
        .nm\_flags = 0,
        .nm\_filename = nullptr,
        .nm\_register\_func = Init,
        .nm\_modname = "entry",
        .nm\_priv = ((void \*)0),
        .reserved = {0},
    };
    
    extern "C" \_\_attribute\_\_((constructor)) void RegisterEntryModule(void)
    {
        napi\_module\_register(&demoModule);
    }
    
4.  在工程的Index.d.ts文件中定义函数的类型。
    
    export const AddReadOnlyResponseInterceptor: () => number;
    export const RemoveReadOnlyResponseInterceptor: () => number;
    export const StartReadOnlyResponseInterceptors: () => number;
    export const StopReadOnlyResponseInterceptors: () => number;
    export const RemoveAllReadOnlyResponseInterceptors: () => number;
    export const AddModifyRequestInterceptor: () => number;
    export const RemoveModifyRequestInterceptor: () => number;
    export const StartModifyRequestInterceptors: () => number;
    export const StopModifyRequestInterceptors: () => number;
    export const RemoveAllModifyRequestInterceptors: () => number;
    export const AddModifyResponseInterceptor: () => number;
    export const RemoveModifyResponseInterceptor: () => number;
    export const StartModifyResponseInterceptors: () => number;
    export const StopModifyResponseInterceptors: () => number;
    export const RemoveAllModifyResponseInterceptors: () => number;
    
5.  在Index.ets文件中对上述封装好的接口进行调用。
    
    import { hilog } from '@kit.PerformanceAnalysisKit';
    import httpInterceptor from 'libentry.so';
    import { http } from '@kit.NetworkKit';
    
    const LOG\_TAG: string = 'HttpInterceptorDemo';
    const HTTP\_URL\_BAIDU: string = "http://www.baidu.com";
    
    @Entry
    @Component
    struct Index {
      @State message: string = 'ReadOnly Network Kit Response Interceptor';
      scroller: Scroller = new Scroller();
    
      build() {
        Scroll(this.scroller) {
          Column() {
            Text(this.message)
              .fontSize(20)
              .margin({ bottom: 30 })
    
            Button('Add ReadOnly Response Interceptor')
              .margin({ top: 10 })
              .width(350)
              .borderRadius(8)
              .id('AddInterceptor')
              .onClick(() => {
                let ret = httpInterceptor.AddReadOnlyResponseInterceptor();
                hilog.info(0x0000, LOG\_TAG, \`AddReadOnlyResponseInterceptor ret: ${ret}\`);
              })
    
            Button('Start ReadOnly Response Interceptors')
              .id('StartInterceptors')
              .width(350)
              .borderRadius(8)
              .margin({ top: 15 })
              .onClick(() => {
                let ret = httpInterceptor.StartReadOnlyResponseInterceptors();
                hilog.info(0x0000, LOG\_TAG, \`StartReadOnlyResponseInterceptors ret: ${ret}\`);
              })
    
            Button('Stop ReadOnly Response Interceptors')
              .id('StopInterceptors')
              .width(350)
              .borderRadius(8)
              .margin({ top: 15 })
              .onClick(() => {
                let ret = httpInterceptor.StopReadOnlyResponseInterceptors();
                hilog.info(0x0000, LOG\_TAG, \`StopReadOnlyResponseInterceptors ret: ${ret}\`);
              })
    
            Button('Remove ReadOnly Response Interceptor')
              .id('RemoveInterceptor')
              .width(350)
              .borderRadius(8)
              .margin({ top: 15 })
              .onClick(() => {
                let ret = httpInterceptor.RemoveReadOnlyResponseInterceptor();
                hilog.info(0x0000, LOG\_TAG, \`RemoveReadOnlyResponseInterceptor ret: ${ret}\`);
              })
    
            Button('Remove All ReadOnly Response Interceptors')
              .id('RemoveAllInterceptors')
              .width(350)
              .borderRadius(8)
              .margin({ top: 15, bottom: 30 })
              .onClick(() => {
                let ret = httpInterceptor.RemoveAllReadOnlyResponseInterceptors();
                hilog.info(0x0000, LOG\_TAG, \`RemoveAllReadOnlyResponseInterceptors ret: ${ret}\`);
              })
    
            Text('Modify Network Kit Request Interceptor')
              .fontSize(20)
              .margin({ bottom: 30 })
    
            Button('Add Modify Request Interceptor')
              .id('AddModifyRequestInterceptor')
              .width(350)
              .borderRadius(8)
              .margin({ top: 10 })
              .onClick(() => {
                let ret = httpInterceptor.AddModifyRequestInterceptor();
                hilog.info(0x0000, LOG\_TAG, \`AddModifyRequestInterceptor ret: ${ret}\`);
              })
    
            Button('Start Modify Request Interceptors')
              .id('StartModifyRequestInterceptors')
              .width(350)
              .borderRadius(8)
              .margin({ top: 15 })
              .onClick(() => {
                let ret = httpInterceptor.StartModifyRequestInterceptors();
                hilog.info(0x0000, LOG\_TAG, \`StartModifyRequestInterceptors ret: ${ret}\`);
              })
    
            Button('Stop Modify Request Interceptors')
              .id('StopModifyRequestInterceptors')
              .width(350)
              .borderRadius(8)
              .margin({ top: 15 })
              .onClick(() => {
                let ret = httpInterceptor.StopModifyRequestInterceptors();
                hilog.info(0x0000, LOG\_TAG, \`StopModifyRequestInterceptors ret: ${ret}\`);
              })
    
            Button('Remove Modify Request Interceptor')
              .id('RemoveModifyRequestInterceptor')
              .width(350)
              .borderRadius(8)
              .margin({ top: 15 })
              .onClick(() => {
                let ret = httpInterceptor.RemoveModifyRequestInterceptor();
                hilog.info(0x0000, LOG\_TAG, \`RemoveModifyRequestInterceptor ret: ${ret}\`);
              })
    
            Button('Remove All Modify Request Interceptors')
              .id('RemoveAllModifyRequestInterceptors')
              .width(350)
              .borderRadius(8)
              .margin({ top: 15, bottom: 30 })
              .onClick(() => {
                let ret = httpInterceptor.RemoveAllModifyRequestInterceptors();
                hilog.info(0x0000, LOG\_TAG, \`RemoveAllModifyRequestInterceptors ret: ${ret}\`);
              })
    
            Text('Modify Network Kit Response Interceptor')
              .fontSize(20)
              .margin({ bottom: 30 })
    
            Button('Add Modify Response Interceptor')
              .id('AddModifyResponseInterceptor')
              .width(350)
              .borderRadius(8)
              .margin({ top: 10 })
              .onClick(() => {
                let ret = httpInterceptor.AddModifyResponseInterceptor();
                hilog.info(0x0000, LOG\_TAG, \`AddModifyResponseInterceptor ret: ${ret}\`);
              })
    
            Button('Start Modify Response Interceptors')
              .id('StartModifyResponseInterceptors')
              .width(350)
              .borderRadius(8)
              .margin({ top: 15 })
              .onClick(() => {
                let ret = httpInterceptor.StartModifyResponseInterceptors();
                hilog.info(0x0000, LOG\_TAG, \`StartModifyResponseInterceptors ret: ${ret}\`);
              })
    
            Button('Stop Modify Response Interceptors')
              .id('StopModifyResponseInterceptors')
              .width(350)
              .borderRadius(8)
              .margin({ top: 15 })
              .onClick(() => {
                let ret = httpInterceptor.StopModifyResponseInterceptors();
                hilog.info(0x0000, LOG\_TAG, \`StopModifyResponseInterceptors ret: ${ret}\`);
              })
    
            Button('Remove Modify Response Interceptor')
              .id('RemoveModifyResponseInterceptor')
              .width(350)
              .borderRadius(8)
              .margin({ top: 15 })
              .onClick(() => {
                let ret = httpInterceptor.RemoveModifyResponseInterceptor();
                hilog.info(0x0000, LOG\_TAG, \`RemoveModifyResponseInterceptor ret: ${ret}\`);
              })
    
            Button('Remove All Modify Response Interceptors')
              .id('RemoveAllModifyResponseInterceptors')
              .width(350)
              .borderRadius(8)
              .margin({ top: 15, bottom: 30 })
              .onClick(() => {
                let ret = httpInterceptor.RemoveAllModifyResponseInterceptors();
                hilog.info(0x0000, LOG\_TAG, \`RemoveAllModifyResponseInterceptors ret: ${ret}\`);
              })
    
            Text('Send HTTP Request')
              .fontSize(20)
              .margin({ bottom: 30 })
    
            Button('Send HTTP Request')
              .id('networkRequest')
              .width(350)
              .borderRadius(8)
              .margin({ top: 15 })
              .onClick(() => {
                let httpRequest: http.HttpRequest = http.createHttp();
                let options: http.HttpRequestOptions = {
                  method: http.RequestMethod.POST,
                };
                httpRequest.request(HTTP\_URL\_BAIDU, options, (err: BusinessError, res: http.HttpResponse) => {
                  if (err) {
                    hilog.info(0x0000, LOG\_TAG, \`request fail, error code: ${err.code}, msg: ${err.message}\`);
                    httpRequest.destroy();
                  } else {
                    hilog.info(0x0000, LOG\_TAG, \`res:${JSON.stringify(res)}\`);
                    httpRequest.destroy();
                  }
                });
              })
          }
          .width('100%')
        }
      }
    }
    
6.  配置CMakeLists.txt，本模块需要用到的共享库是libhttp\_interceptor.so，在工程自动生成的CMakeLists.txt中的target\_link\_libraries中添加此共享库。
    
    注意：如图所示，在add\_library中的entry是工程自动生成的module name，若要做修改，需和步骤 3 中.nm\_modname保持一致。
    
    ![](https://contentcenter-vali-drcn.dbankcdn.cn/pvt_2/DeveloperAlliance_scene_100_1/b4/v3/BUlD5HC_RYGcJI3sManpEg/zh-cn_image_0000002594828590.png?HW-CC-KV=V1&HW-CC-Date=20260612T073431Z&HW-CC-Expire=86400&HW-CC-Sign=0E41D1CBF24CCDBC1668DD5034341651ACEB30991B401B6C8677826C7B21CCA1)
    
7.  调用HTTP全局拦截器C API接口要求应用拥有ohos.permission.INTERNET权限，在module.json5中的requestPermissions项添加该权限。
    

完成上述步骤后，工程搭建已全部完成，后续可连接设备运行工程并查看日志。

#### 测试步骤

1.  连接设备，使用DevEco Studio打开搭建好的工程。
    
2.  运行工程，设备上会弹出以下图片所示界面。
    

![](https://contentcenter-vali-drcn.dbankcdn.cn/pvt_2/DeveloperAlliance_scene_100_1/a1/v3/UbWSpzpBTYSHykhl3AZzIg/zh-cn_image_0000002625188037.png?HW-CC-KV=V1&HW-CC-Date=20260612T073431Z&HW-CC-Expire=86400&HW-CC-Sign=844151B73C63818A4F431FC618292AEED566F0AB6054FA27A2F60A5324529FF9)

![](https://contentcenter-vali-drcn.dbankcdn.cn/pvt_2/DeveloperAlliance_scene_100_1/e5/v3/-lLQLDKuQGqHZ0p_mMlQYA/zh-cn_image_0000002625108181.png?HW-CC-KV=V1&HW-CC-Date=20260612T073431Z&HW-CC-Expire=86400&HW-CC-Sign=FB6874DFF58A86A9F62DFC528092224E1183D2B1357CE98085ADD5CE660CEE76)

*   点击Add Read Only Response Interceptor按钮，添加一个HTTP全局只读响应拦截器。

![](https://contentcenter-vali-drcn.dbankcdn.cn/pvt_2/DeveloperAlliance_scene_100_1/32/v3/JfpI1WRgTN-vaf3yxd3OUA/zh-cn_image_0000002594668664.png?HW-CC-KV=V1&HW-CC-Date=20260612T073431Z&HW-CC-Expire=86400&HW-CC-Sign=92DA21C48746A0EE9705C6385DEE34DD47411C3FF8A6A4E0788442B6C5CDBB7A)

*   点击Start Read Only Response Interceptors按钮，启用组ID为1的所有只读响应拦截器。

![](https://contentcenter-vali-drcn.dbankcdn.cn/pvt_2/DeveloperAlliance_scene_100_1/15/v3/6eO926OFTCOtQLoTUMx26Q/zh-cn_image_0000002594828592.png?HW-CC-KV=V1&HW-CC-Date=20260612T073431Z&HW-CC-Expire=86400&HW-CC-Sign=9B3B92C22FB35E0C0F1F7B4A496F28FFE94D97424E7B008812D401A34CCD5653)

*   点击Add Modify Request Interceptor按钮，添加一个HTTP全局可修改请求拦截器。

![](https://contentcenter-vali-drcn.dbankcdn.cn/pvt_2/DeveloperAlliance_scene_100_1/d0/v3/QGpPL7Y2RTqxZnsExEA73w/zh-cn_image_0000002625188039.png?HW-CC-KV=V1&HW-CC-Date=20260612T073431Z&HW-CC-Expire=86400&HW-CC-Sign=EC9B3C14DB01DBBFB2F9E384A73CC4064196A909336CCF1C5FE61E7A40C4473B)

*   点击Start Modify Request Interceptors按钮，启用组ID为2的所有可修改请求拦截器。

![](https://contentcenter-vali-drcn.dbankcdn.cn/pvt_2/DeveloperAlliance_scene_100_1/e0/v3/rQlHmfSeQVeJXclhs0b4Mg/zh-cn_image_0000002625108183.png?HW-CC-KV=V1&HW-CC-Date=20260612T073431Z&HW-CC-Expire=86400&HW-CC-Sign=ACA46003A8D52979A225C21B887C2554BD2BE9E8475DE3EA40DD3DCA3BCD3FEA)

*   点击Add Modify Response Interceptor按钮，添加一个HTTP全局可修改响应拦截器。

![](https://contentcenter-vali-drcn.dbankcdn.cn/pvt_2/DeveloperAlliance_scene_100_1/c0/v3/UnOtIs5OR7e3RPBkW0Fdzg/zh-cn_image_0000002594668666.png?HW-CC-KV=V1&HW-CC-Date=20260612T073431Z&HW-CC-Expire=86400&HW-CC-Sign=7007F10D67F9BE7ED5DD0F5DFAF94514F1F8FAA6ECC6147E01E82293EB713160)

*   点击Start Modify Response Interceptors按钮，启用组ID为3的所有可修改响应拦截器。

![](https://contentcenter-vali-drcn.dbankcdn.cn/pvt_2/DeveloperAlliance_scene_100_1/a/v3/kzTnzgGWQeGG14wATMzerQ/zh-cn_image_0000002594828594.png?HW-CC-KV=V1&HW-CC-Date=20260612T073431Z&HW-CC-Expire=86400&HW-CC-Sign=263B3F0EA916694F54081A87057E85CE6526B82A2A7A79D21EB846769654D0B4)

*   点击Send HTTP Request按钮，拦截器会捕获响应并打印相关信息到日志。

![](https://contentcenter-vali-drcn.dbankcdn.cn/pvt_2/DeveloperAlliance_scene_100_1/ca/v3/mefHSeThTSWUsXF7wmjVBw/zh-cn_image_0000002625188041.png?HW-CC-KV=V1&HW-CC-Date=20260612T073431Z&HW-CC-Expire=86400&HW-CC-Sign=F87EE2F1EDE7186F2528B77DDC3B490694F2BDA29B4719C8CD3A3AAE160DDCED)

*   点击Stop Read Only Response Interceptors按钮，停用组ID为1的只读响应拦截器。

![](https://contentcenter-vali-drcn.dbankcdn.cn/pvt_2/DeveloperAlliance_scene_100_1/69/v3/mTWkkCEpR2qPB7FQ18bi9w/zh-cn_image_0000002625108185.png?HW-CC-KV=V1&HW-CC-Date=20260612T073431Z&HW-CC-Expire=86400&HW-CC-Sign=1AE14113F2786F9E410FBEAE6943AFDB3B31C38E6EB32F733F604315FE6D52B3)

*   点击Stop Modify Request Interceptors按钮，停用组ID为2的可修改请求拦截器。

![](https://contentcenter-vali-drcn.dbankcdn.cn/pvt_2/DeveloperAlliance_scene_100_1/38/v3/yiwi2u79TyazUOiPjJPdcA/zh-cn_image_0000002594668668.png?HW-CC-KV=V1&HW-CC-Date=20260612T073431Z&HW-CC-Expire=86400&HW-CC-Sign=06DE6AE1424EFE133793E7EA0DE1AF2FABCBA9905B0E6A2ACF20183F2B46F424)

*   点击Stop Modify Response Interceptors按钮，停用组ID为3的可修改响应拦截器。

![](https://contentcenter-vali-drcn.dbankcdn.cn/pvt_2/DeveloperAlliance_scene_100_1/5f/v3/qtzjRt-CQ4ehRrCjZOJYDg/zh-cn_image_0000002594828596.png?HW-CC-KV=V1&HW-CC-Date=20260612T073431Z&HW-CC-Expire=86400&HW-CC-Sign=6F7D7F062851FCDC3313847C742D753D5EBEED94685F97551DC4AE13C3457ACF)

*   点击Remove Read Only Response Interceptor按钮，移除之前添加的只读响应拦截器。

![](https://contentcenter-vali-drcn.dbankcdn.cn/pvt_2/DeveloperAlliance_scene_100_1/ea/v3/RZweM_n2T7CfYe8HxfEQeg/zh-cn_image_0000002625188043.png?HW-CC-KV=V1&HW-CC-Date=20260612T073431Z&HW-CC-Expire=86400&HW-CC-Sign=7F272D6DC0DC3F36CA1D80050454DC68A2C9522E5FF022A071F0C97AF816F698)

*   点击Remove Modify Request Interceptor按钮，移除之前添加的可修改请求拦截器。

![](https://contentcenter-vali-drcn.dbankcdn.cn/pvt_2/DeveloperAlliance_scene_100_1/cc/v3/5TN2DfGQTxGueZJnVZlRYA/zh-cn_image_0000002625108187.png?HW-CC-KV=V1&HW-CC-Date=20260612T073431Z&HW-CC-Expire=86400&HW-CC-Sign=097322689E1286DF87D1365AAEC927F21196E0F5F5BAEBD713A04BC30E32FD35)

*   点击Remove Modify Response Interceptor按钮，移除之前添加的可修改响应拦截器。

![](https://contentcenter-vali-drcn.dbankcdn.cn/pvt_2/DeveloperAlliance_scene_100_1/92/v3/gc0vh1d_RSqTPCRwuDVjDQ/zh-cn_image_0000002594668670.png?HW-CC-KV=V1&HW-CC-Date=20260612T073431Z&HW-CC-Expire=86400&HW-CC-Sign=EEFEDF6AA86F7ADBD68EFFBBB381CB1D155296B6F3C0B0E80EC4731ACCDDAFD6)

*   点击Remove All Read Only Response Interceptors按钮，移除组ID为1的所有只读响应拦截器。

![](https://contentcenter-vali-drcn.dbankcdn.cn/pvt_2/DeveloperAlliance_scene_100_1/26/v3/LsRP0wWET7qjjLE0MDbTgA/zh-cn_image_0000002594828598.png?HW-CC-KV=V1&HW-CC-Date=20260612T073431Z&HW-CC-Expire=86400&HW-CC-Sign=718C8585695A7B8404AF8900F8A91E0CEBD5F01EEA6C1B8145546C885E36EA04)

*   点击Remove All Modify Request Interceptors按钮，移除组ID为2的所有可修改请求拦截器。

![](https://contentcenter-vali-drcn.dbankcdn.cn/pvt_2/DeveloperAlliance_scene_100_1/45/v3/xi0oEhc2R72NfCZlUWw6ew/zh-cn_image_0000002625188045.png?HW-CC-KV=V1&HW-CC-Date=20260612T073431Z&HW-CC-Expire=86400&HW-CC-Sign=3CD301C34DE9043DAE19E663580443F345E662CCB75E24B706E13BB177035F4F)

*   点击Remove All Modify Response Interceptors按钮，移除组ID为3的所有可修改响应拦截器。

![](https://contentcenter-vali-drcn.dbankcdn.cn/pvt_2/DeveloperAlliance_scene_100_1/f3/v3/yZ6g0nG8TMmFyqr3JszvUw/zh-cn_image_0000002625108189.png?HW-CC-KV=V1&HW-CC-Date=20260612T073431Z&HW-CC-Expire=86400&HW-CC-Sign=F9523756BCBC4DAFFE3DA30868FD131850E650662C382DB6F8F890404326D96A)