使用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/b5/v3/v90PWAXySxO-cXizNINGwA/zh-cn_image_0000002633849194.png?HW-CC-KV=V1&HW-CC-Date=20260709T132435Z&HW-CC-Expire=86400&HW-CC-Sign=D13D53A9618EED6BA9C27574FF10558A414E5F1649D956A9CDAA46AEA9ECCD03)
    
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/4b/v3/WatUnR7NSvKE1Xdr_NYuIQ/zh-cn_image_0000002634009098.png?HW-CC-KV=V1&HW-CC-Date=20260709T132435Z&HW-CC-Expire=86400&HW-CC-Sign=932DA35DC15B4F9F97141A1C525C9D10CD1C85C13FD61C8EE25D0E15106E9AA9)

![](https://contentcenter-vali-drcn.dbankcdn.cn/pvt_2/DeveloperAlliance_scene_100_1/0f/v3/WAiniV11RJa06mMPuq2IRQ/zh-cn_image_0000002664208247.png?HW-CC-KV=V1&HW-CC-Date=20260709T132435Z&HW-CC-Expire=86400&HW-CC-Sign=6EDAE31A7CC239EDD53C045C12F61A58020AC48B90927E5579BF18F1205297A3)

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

![](https://contentcenter-vali-drcn.dbankcdn.cn/pvt_2/DeveloperAlliance_scene_100_1/ff/v3/E5egF-miQrym7i0jrJep1w/zh-cn_image_0000002664328307.png?HW-CC-KV=V1&HW-CC-Date=20260709T132435Z&HW-CC-Expire=86400&HW-CC-Sign=CCFD6986C7916F2F7AD0CED0846B80B80CC363C7D75C869C8401C62632861705)

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

![](https://contentcenter-vali-drcn.dbankcdn.cn/pvt_2/DeveloperAlliance_scene_100_1/9a/v3/747wMtGFQXGj4L3btyh-kg/zh-cn_image_0000002633849196.png?HW-CC-KV=V1&HW-CC-Date=20260709T132435Z&HW-CC-Expire=86400&HW-CC-Sign=81A72868C3FD0FB43A59998977ADBE7ADFA59456FCFA4AC1F419941FA605F90C)

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

![](https://contentcenter-vali-drcn.dbankcdn.cn/pvt_2/DeveloperAlliance_scene_100_1/e7/v3/iZZSYiECQfWxqZhaerfr9w/zh-cn_image_0000002634009100.png?HW-CC-KV=V1&HW-CC-Date=20260709T132435Z&HW-CC-Expire=86400&HW-CC-Sign=9CD48D021455ED03AA9B41D45905AFBAB850A18369DF3B38334C4AA93A2752C6)

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

![](https://contentcenter-vali-drcn.dbankcdn.cn/pvt_2/DeveloperAlliance_scene_100_1/fb/v3/zCbiqfDSTo26DfQIWE4tgg/zh-cn_image_0000002664208249.png?HW-CC-KV=V1&HW-CC-Date=20260709T132435Z&HW-CC-Expire=86400&HW-CC-Sign=7B773B0F29AC33F472DBA06197182B1AB77F60BE68BC57999FA77E67B85906FB)

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

![](https://contentcenter-vali-drcn.dbankcdn.cn/pvt_2/DeveloperAlliance_scene_100_1/9d/v3/arzh9E-DSF6IsmBqssWBfg/zh-cn_image_0000002664328309.png?HW-CC-KV=V1&HW-CC-Date=20260709T132435Z&HW-CC-Expire=86400&HW-CC-Sign=887EDD32C3F65D78C6977CBF93898C266ED7D7B08EAFCCF2931F88A87E4665C0)

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

![](https://contentcenter-vali-drcn.dbankcdn.cn/pvt_2/DeveloperAlliance_scene_100_1/91/v3/T_jHWlhHR2OS75wl1RmlKg/zh-cn_image_0000002633849198.png?HW-CC-KV=V1&HW-CC-Date=20260709T132435Z&HW-CC-Expire=86400&HW-CC-Sign=97E6FE67AE6328D9755F1FD62B5780C95570B17F823C702203AF143F9691FE64)

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

![](https://contentcenter-vali-drcn.dbankcdn.cn/pvt_2/DeveloperAlliance_scene_100_1/ff/v3/EflzDDSJRAeh5SEnWW1tzw/zh-cn_image_0000002634009102.png?HW-CC-KV=V1&HW-CC-Date=20260709T132435Z&HW-CC-Expire=86400&HW-CC-Sign=9B911C6F5489BAE8CE8FBE7EE58971E3D757D1734A246393C56CBFF8D49DCF91)

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

![](https://contentcenter-vali-drcn.dbankcdn.cn/pvt_2/DeveloperAlliance_scene_100_1/9c/v3/SE_bxKx6QBu5qO8wV-ijAQ/zh-cn_image_0000002664208251.png?HW-CC-KV=V1&HW-CC-Date=20260709T132435Z&HW-CC-Expire=86400&HW-CC-Sign=7E17652D7F00C76C0DAEA2704E4E16A7C448771B7469B4A712853F7BEF5C5274)

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

![](https://contentcenter-vali-drcn.dbankcdn.cn/pvt_2/DeveloperAlliance_scene_100_1/57/v3/qFqLW9B4TxaUy2aMDZRn3w/zh-cn_image_0000002664328311.png?HW-CC-KV=V1&HW-CC-Date=20260709T132435Z&HW-CC-Expire=86400&HW-CC-Sign=5F2009906B8FBDAB2FADCBE99481F08E6067D90238919B4B26DA2C0CED3B771B)

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

![](https://contentcenter-vali-drcn.dbankcdn.cn/pvt_2/DeveloperAlliance_scene_100_1/ff/v3/gpA6JqQIS4i-7bOg6vajvg/zh-cn_image_0000002633849200.png?HW-CC-KV=V1&HW-CC-Date=20260709T132435Z&HW-CC-Expire=86400&HW-CC-Sign=50BFD60B6E2C8F5E9E8A4A3C87D04F94F1B2D2CA7A9BF0EDC48541518E3F576A)

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

![](https://contentcenter-vali-drcn.dbankcdn.cn/pvt_2/DeveloperAlliance_scene_100_1/3/v3/MtiLDKN9T82D8QGG1a1CKA/zh-cn_image_0000002634009104.png?HW-CC-KV=V1&HW-CC-Date=20260709T132435Z&HW-CC-Expire=86400&HW-CC-Sign=2F363F147FFA568DE4259DBE981D729A154520300E5F42E7CBF004382523BD59)

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

![](https://contentcenter-vali-drcn.dbankcdn.cn/pvt_2/DeveloperAlliance_scene_100_1/2f/v3/MzMuMChuQTa98OnnlN5-FQ/zh-cn_image_0000002664208253.png?HW-CC-KV=V1&HW-CC-Date=20260709T132435Z&HW-CC-Expire=86400&HW-CC-Sign=8D9E75154CB2EE96FF6CD7B1A892903893525283AE3C528E910056E8F7A5C0A5)

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

![](https://contentcenter-vali-drcn.dbankcdn.cn/pvt_2/DeveloperAlliance_scene_100_1/e3/v3/GjK3td8DRPyTuuwVvncXZQ/zh-cn_image_0000002664328313.png?HW-CC-KV=V1&HW-CC-Date=20260709T132435Z&HW-CC-Expire=86400&HW-CC-Sign=346A3E75083FDDF146A791C7E5976953DC0D8E933EAFF6253F7CED7435B62FF4)

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

![](https://contentcenter-vali-drcn.dbankcdn.cn/pvt_2/DeveloperAlliance_scene_100_1/9c/v3/H7sChLvpTZi0jZCJAIZKUw/zh-cn_image_0000002633849202.png?HW-CC-KV=V1&HW-CC-Date=20260709T132435Z&HW-CC-Expire=86400&HW-CC-Sign=93A85E0348901109CEB9C37A4AA6788F08AD98542471BCED7038784B211968FF)

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

![](https://contentcenter-vali-drcn.dbankcdn.cn/pvt_2/DeveloperAlliance_scene_100_1/33/v3/3IGKo0KvTnmDLDYBGGUxyQ/zh-cn_image_0000002634009106.png?HW-CC-KV=V1&HW-CC-Date=20260709T132435Z&HW-CC-Expire=86400&HW-CC-Sign=C8B5F48BF266B6BE298DEB90143966B09B5984AD3F79F43D925FB771B7BB7CFF)

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

![](https://contentcenter-vali-drcn.dbankcdn.cn/pvt_2/DeveloperAlliance_scene_100_1/d7/v3/1YGSyw-BR5uMOdE79a7HLA/zh-cn_image_0000002664208255.png?HW-CC-KV=V1&HW-CC-Date=20260709T132435Z&HW-CC-Expire=86400&HW-CC-Sign=97EB95E50305BD3A073EF003944B79F87DD019643A3764FDC8B8CD29C675D4B2)