鸿蒙HarmonyOS NEXT(开发进阶)实现一个基于鸿蒙API的HTTP服务器实践案例

  鸿蒙NEXT开发实战往期必看文章:

一分钟了解”纯血版!鸿蒙HarmonyOS Next应用开发!

“非常详细的” 鸿蒙HarmonyOS Next应用开发学习路线!(从零基础入门到精通)

HarmonyOS NEXT应用开发案例实践总结合(持续更新......)

HarmonyOS NEXT应用开发性能优化实践总结(持续更新......)


1. 鸿蒙HTTP服务器可行性分析

看到这个题目,可能有的小伙伴会有一些疑问:

“鸿蒙API从9到12我都翻烂了,也没见提供HTTP服务器的接口啊”

“我BUG写得少,你可不要骗我”

的确,目前的鸿蒙API没有提供HTTP服务端的实现接口,但是我们知道,HTTP协议是基于TCP的,而鸿蒙API10提供了TCPSocketServer类,包含了如下几个关键接口:

listen(address: NetAddress): Promise<void>

监听方法,绑定IP地址和端口,端口可以指定或由系统随机分配。成功调用该方法后,TCPSocketServer对象监听并接受与此套接字建立的TCPSocket连接。

on(type: 'connect', callback: Callback<TCPSocketConnection>): void

订阅TCPSocketServer的连接事件,在新的客户端套接字连接上以后,会触发callback回调,在回调中包含TCPSocketConnection对象,该对象就表示TCPSocket客户端与服务端的连接。

TCPSocketConnection是服务端和客户端通讯的基础,提供了发送数据到客户端的方法:

send(options: TCPSendOptions): Promise<void>

还提供了订阅客户端消息接收的事件:

on(type: 'message', callback: Callback<SocketMessageInfo>): void

在这个事件的callback回调里,包含了SocketMessageInfo参数,该参数的属性message就是客户端发送过来的消息。

通过上述几个接口,我们就可以在服务端开启TCP监听,并且处理客户端的连接和消息收发。

再来说一下HTTP协议,众所周知,HTTP协议是一个简单的请求响应协议,根据RFC 9112,HTTP协议1.1版本的消息格式如下所示:

  HTTP-message = start-line CRLF
                   *( field-line CRLF )
                   CRLF
                   [ message-body ]

其中,start-line表示起始行,CRLF表示回车换行符号,field-line表示首部字段行,*( field-line CRLF )说明首部字段可以是零个或者多个,最后的[ message-body ]表示可选的消息正文;因为消息分为请求消息和应答消息,所以起始行又可以分为请求行和状态行,如下所示:

start-line     = request-line / status-line

当然,HTTP的协议还是有一点复杂的,这里就不展开了,不过我们明白,只要我们按照协议格式构造出了请求应答的文本,然后使用TCP协议作为传输层进行收发即可。

有了上面的API接口,加上HTTP协议的格式,就可以打造一个最简单的HTTP服务端了。

2. 实现HTTP服务器示例

本示例运行后的界面如下所示:

cke_260763.jpg

输入要监听的端口,然后单击“启动”按钮,即可在127.0.0.1上启动对端口的TCP协议监听了。然后在请求地址栏输入服务端地址,再单击“请求”按钮,既可请求刚创建的HTTP服务器,效果如图所示:

cke_410364.jpg

这里实现的HTTP服务器是这样的,接收到客户端的请求后,会把客户端发送的信息作为网页的内容反馈给客户端,也就是上图中看到的这些内容:

cke_493678.png

下面详细介绍创建该应用的步骤。

步骤1:创建Empty Ability项目。

步骤2:在module.json5配置文件加上对权限的声明:

"requestPermissions": [
      {
        "name": "ohos.permission.INTERNET"
      }
    ]

这里添加了获取互联网信息的权限。

步骤3:在Index.ets文件里添加如下的代码:

import { socket } from '@kit.NetworkKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { util } from '@kit.ArkTS';
import { webview } from '@kit.ArkWeb';

let tcpServer: socket.TCPSocketServer = socket.constructTCPSocketServerInstance();

@Entry
@Component
struct Index {
  @State message: string = '最简单的HTTP服务器示例';
  @State port: number = 8080
  @State running: boolean = false
  @State msgHistory: string = ''
  @State webUrl: string = "https://developer.huawei.com/"
  scroller: Scroller = new Scroller()
  webScroller: Scroller = new Scroller()
  controller: webview.WebviewController = new webview.WebviewController()

  build() {
    RelativeContainer() {
      Text(this.message)
        .id('txtTitle')
        .fontSize(20)
        .fontWeight(FontWeight.Bold)
        .alignRules({
          middle: { anchor: '__container__', align: HorizontalAlign.Center },
          top: { anchor: '__container__', align: VerticalAlign.Top }
        })
        .padding(10)

      Text("端口")
        .id('txtPort')
        .fontSize(15)
        .height(40)
        .alignRules({
          left: { anchor: '__container__', align: HorizontalAlign.Start },
          top: { anchor: 'txtTitle', align: VerticalAlign.Bottom }
        })
        .padding(10)

      TextInput({ text: this.port.toString() })
        .onChange((value) => {
          this.port = parseInt(value)
        })
        .type(InputType.Number)
        .width(80)
        .height(40)
        .id('txtInputPort')
        .fontSize(15)
        .alignRules({
          left: { anchor: 'txtPort', align: HorizontalAlign.End },
          top: { anchor: 'txtPort', align: VerticalAlign.Top }
        })
        .padding(10)

      Button(this.running ? "停止" : "启动")
        .onClick(() => {
          this.running = !this.running
          if (this.running) {
            this.start()
          } else {
            this.stop()
          }

        })
        .height(40)
        .width(80)
        .id('butRun')
        .fontSize(15)
        .alignRules({
          right: { anchor: '__container__', align: HorizontalAlign.End },
          top: { anchor: 'txtPort', align: VerticalAlign.Top }
        })
        .padding(10)

      Scroll(this.scroller) {
        Text(this.msgHistory)
          .textAlign(TextAlign.Start)
          .padding(10)
          .width('100%')
          .fontSize(12)
          .backgroundColor(0xeeeeee)
      }
      .alignRules({
        left: { anchor: '__container__', align: HorizontalAlign.Start },
        top: { anchor: 'butRun', align: VerticalAlign.Bottom }
      })
      .align(Alignment.Top)
      .backgroundColor(0xeeeeee)
      .height(200)
      .scrollable(ScrollDirection.Vertical)
      .scrollBar(BarState.On)
      .scrollBarWidth(20)
      .padding(10)
      .id('scrollHis')

      Text("请求地址")
        .id('txtUrl')
        .fontSize(15)
        .height(40)
        .alignRules({
          left: { anchor: '__container__', align: HorizontalAlign.Start },
          top: { anchor: 'scrollHis', align: VerticalAlign.Bottom }
        })
        .padding(10)

      TextInput({ text: this.webUrl.toString() })
        .onChange((value) => {
          this.webUrl = value
        })
        .height(40)
        .id('txtInputWebUrl')
        .fontSize(15)
        .alignRules({
          left: { anchor: 'txtUrl', align: HorizontalAlign.End },
          top: { anchor: 'txtUrl', align: VerticalAlign.Top },
          right: { anchor: 'butWeb', align: HorizontalAlign.Start }
        })
        .padding(10)

      Button("请求")
        .onClick(() => {
          this.controller.loadUrl(this.webUrl)
        })
        .height(40)
        .width(80)
        .id('butWeb')
        .fontSize(15)
        .alignRules({
          right: { anchor: '__container__', align: HorizontalAlign.End },
          top: { anchor: 'txtUrl', align: VerticalAlign.Top }
        })
        .padding(10)

      Scroll(this.webScroller) {
        Web({ src: this.webUrl, controller: this.controller })
          .padding(10)
          .width('100%')
          .backgroundColor(0xeeeeee)
          .textZoomRatio(200)
      }
      .alignRules({
        left: { anchor: '__container__', align: HorizontalAlign.Start },
        top: { anchor: 'txtUrl', align: VerticalAlign.Bottom },
        bottom: { anchor: '__container__', align: VerticalAlign.Bottom }
      })
      .backgroundColor(0xeeeeee)
      .scrollable(ScrollDirection.Vertical)
      .scrollBar(BarState.On)
      .scrollBarWidth(20)

    }
    .height('100%')
    .width('100%')
  }

  start() {
    this.webUrl = "http://127.0.0.1:" + this.port.toString()
    let listenAddr: socket.NetAddress = {
      address: '0.0.0.0',
      port: this.port,
      family: 1
    }

    tcpServer.listen(listenAddr, (err: BusinessError) => {
      if (err) {
        this.msgHistory += "listen fail \r\n";
        return;
      }
      this.msgHistory += "listen success \r\n";
    })

    tcpServer.on('connect', (clientSocket: socket.TCPSocketConnection) => {
      clientSocket.on('message', (msgInfo: socket.SocketMessageInfo) => {
        let requestMsg = buf2String(msgInfo.message)
        this.msgHistory += requestMsg + "\r\n"
        let resp = buildRespString(requestMsg)
        clientSocket.send({ data: resp })
      })
    });
  }

  stop() {
    tcpServer.off('connect')
  }
}

//构造给客户端的应答内容
function buildRespString(content: string) {
  let result: string = ""
  let bodyContent = "<html>"
  bodyContent += "<head>"
  bodyContent += "<title>"
  bodyContent += "HTTP服务器模拟"
  bodyContent += "</title>"
  bodyContent += "</head>"
  bodyContent += "<body>"
  bodyContent += "<h1>"
  bodyContent += "浏览器发送的请求信息"
  bodyContent += "</h1>"
  bodyContent += "<pre><h2>"
  bodyContent += content
  bodyContent += "</h2></pre>"
  bodyContent += "</body>"
  bodyContent += "</html>"

  let textEncoder = new util.TextEncoder();
  let contentBuf = textEncoder.encodeInto(bodyContent)

  result += "HTTP/1.1 200 OK \r\n"
  result += "Content-Type: text/html; charset=utf-8 \r\n"
  result += `Content-Length: ${contentBuf.length} \r\n`
  result += "\r\n"
  result += bodyContent

  return result
}

//ArrayBuffer转utf8字符串
function buf2String(buf: ArrayBuffer) {
  let msgArray = new Uint8Array(buf);
  let textDecoder = util.TextDecoder.create("utf-8");
  return textDecoder.decodeWithStream(msgArray)
}

步骤4:编译运行,可以使用模拟器或者真机,因为当前还处于内测期间,只能使用模拟器。

步骤5:具体的操作过程上面讲过了,就不再赘述了。

3. 关键功能分析

比较关键的代码如下:

    tcpServer.on('connect', (clientSocket: socket.TCPSocketConnection) => {
      clientSocket.on('message', (msgInfo: socket.SocketMessageInfo) => {
        let requestMsg = buf2String(msgInfo.message)
        this.msgHistory += requestMsg + "\r\n"
        let resp = buildRespString(requestMsg)
        clientSocket.send({ data: resp })
      })
    });

这里连接后得到了clientSocket对象,然后继续订阅clientSocket对象的收到客户端消息事件,把消息转换为字符串,然后写入到历史日志msgHistory里。这里buildRespString函数是创建返回给客户端的信息的,最后通过clientSocket的send方法发送给客户端。

虽然本示例比较简单,但是具备了HTTP服务端的基本功能,可以接收客户端的输入,并且可以对客户端的输入进行处理,最后再发送给客户端。

<think>我们正在开发鸿蒙HarmonyOS Next应用,需要使用HTTP工具类。根据引用内容,鸿蒙API内置了HTTP客户端支持(HttpRequest),但暂不支持HTTP服务端(不过可以通过TCP Server自行实现)。用户的需求是获取HTTP工具类的开发使用方法和示例代码。 根据引用[1]和引用[3],我们可以知道: 1. 鸿蒙提供了HttpRequest类用于HTTP客户端请求。 2. 引用[3]中提供了一个示例工程结构,并提到在http.ts文件中封装了http参数和发起请求的接口。 因此,我们将重点介绍如何使用HttpRequest类发起HTTP请求,并提供一个简单的示例代码。 步骤: 1. 配置权限:在config.json中声明网络权限。 2. 导入模块:在代码中导入http模块。 3. 创建HttpRequest对象。 4. 设置请求参数(URL、方法、头部、响应类型等)。 5. 发起请求并处理响应。 注意:鸿蒙HTTP请求是异步的,我们可以使用Promise或者回调函数来处理响应。 示例代码(TypeScript): 以下是一个简单的GET请求示例,以及一个POST请求示例。 首先,确保在config.json中声明网络权限: ```json { "module": { "reqPermissions": [ { "name": "ohos.permission.INTERNET" } ] } } ``` 然后,在代码中: ```typescript import http from '@ohos.net.http'; // 创建HttpRequest对象 let httpRequest = http.createHttp(); // 示例1:GET请求 async function httpGet() { let url = 'https://example.com/api/get'; try { let response = await httpRequest.request( url, { method: http.RequestMethod.GET, header: { 'Content-Type': 'application/json' } } ); // 请求成功,response.result为响应体 console.log('GET Result: ' + JSON.stringify(response.result)); console.log('GET Code: ' + response.responseCode); } catch (error) { console.error('GET Error: ' + JSON.stringify(error)); } } // 示例2:POST请求 async function httpPost() { let url = 'https://example.com/api/post'; try { let response = await httpRequest.request( url, { method: http.RequestMethod.POST, header: { 'Content-Type': 'application/json' }, extraData: { key1: 'value1', key2: 'value2' } } ); console.log('POST Result: ' + JSON.stringify(response.result)); console.log('POST Code: ' + response.responseCode); } catch (error) { console.error('POST Error: ' + JSON.stringify(error)); } } ``` 说明: 1. 使用`http.createHttp()`创建一个HttpRequest实例。 2. 调用`request`方法发起请求,第一个参数是URL,第二个参数是配置对象,包括: - method: 请求方法(GET, POST等) - header: 请求头 - extraData: 请求体(POST请求时使用) 3. 使用async/await处理异步请求,也可以使用回调函数(通过配置对象中的readable和writable属性,但推荐使用Promise方式)。 注意:在实际开发中,建议将HTTP请求封装成工具类,以便复用和管理。 封装示例(参考引用[3]中的http.ts): 我们可以创建一个HttpUtil类,封装GET和POST方法。 http.ts: ```typescript import http from '@ohos.net.http'; export default class HttpUtil { private httpRequest: http.HttpRequest; constructor() { this.httpRequest = http.createHttp(); } // GET请求 async get(url: string, headers: Object = {}): Promise<any> { try { let response = await this.httpRequest.request(url, { method: http.RequestMethod.GET, header: headers }); return response.result; } catch (error) { console.error('HttpUtil GET Error: ' + JSON.stringify(error)); throw error; } } // POST请求 async post(url: string, data: Object, headers: Object = {'Content-Type': 'application/json'}): Promise<any> { try { let response = await this.httpRequest.request(url, { method: http.RequestMethod.POST, header: headers, extraData: data }); return response.result; } catch (error) { console.error('HttpUtil POST Error: ' + JSON.stringify(error)); throw error; } } } ``` 使用封装好的工具类: ```typescript import HttpUtil from './HttpUtil'; // 在页面中 let httpUtil = new HttpUtil(); // 发送GET请求 httpUtil.get('https://example.com/api/get').then(result => { console.log('Result: ' + JSON.stringify(result)); }).catch(error => { console.error('Error: ' + JSON.stringify(error)); }); // 发送POST请求 let data = { key: 'value' }; httpUtil.post('https://example.com/api/post', data).then(result => { console.log('Result: ' + JSON.stringify(result)); }).catch(error => { console.error('Error: ' + JSON.stringify(error)); }); ``` 注意事项: 1. 确保设备有网络连接。 2. 注意异步处理,避免阻塞UI。 3. 错误处理要完善。 以上就是在鸿蒙HarmonyOS Next中使用HTTP工具类的基本方法和示例代码。 根据用户需求,我们提供了开发步骤、示例代码以及封装工具类的建议。用户可以根据实际需求调整封装类。 §§相关问题§§ 1. 鸿蒙HarmonyOS Next中如何处理HTTPS请求? 2. 如何设置HTTP请求的超时时间? 3. 鸿蒙HTTP请求支持哪些方法? 4. 如何上传文件?</think>### 鸿蒙 HarmonyOS Next HTTP 工具类开发指南 #### 一、开发准备 1. **权限声明** 在 `module.json5` 中添加网络权限: ```json "requestPermissions": [ { "name": "ohos.permission.INTERNET" } ] ``` 2. **依赖导入** 在代码中导入 HTTP 模块: ```typescript import http from '@ohos.net.http'; ``` #### 二、核心工具类封装 ```typescript // HttpUtil.ts export default class HttpUtil { private httpRequest: http.HttpRequest; constructor() { this.httpRequest = http.createHttp(); } // GET请求 async get(url: string, params?: Record<string, string>): Promise<any> { const fullUrl = params ? `${url}?${new URLSearchParams(params)}` : url; return this.request(fullUrl, http.RequestMethod.GET); } // POST请求 async post(url: string, data: object): Promise<any> { return this.request(url, http.RequestMethod.POST, data); } // 统一请求方法 private async request( url: string, method: http.RequestMethod, data?: object ): Promise<any> { try { const response = await this.httpRequest.request(url, { method, header: { 'Content-Type': 'application/json' }, extraData: data ? JSON.stringify(data) : undefined }); if (response.responseCode === http.ResponseCode.OK) { return JSON.parse(response.result.toString()); } else { throw new Error(`HTTP Error ${response.responseCode}`); } } catch (error) { console.error(`Request failed: ${JSON.stringify(error)}`); throw error; } } } ``` #### 三、使用示例 ```typescript // MainPage.ets import HttpUtil from './HttpUtil'; @Entry @Component struct MainPage { private http: HttpUtil = new HttpUtil(); async fetchData() { try { // GET示例 const userData = await this.http.get( 'https://api.example.com/users', { id: '123' } ); // POST示例 const loginRes = await this.http.post( 'https://api.example.com/login', { username: 'test', password: '123456' } ); console.log('Login response:', loginRes); } catch (error) { console.error('API Error:', error); } } build() { Column() { Button('获取数据') .onClick(() => this.fetchData()) } } } ``` #### 四、关键功能说明 1. **请求方法支持** - 支持所有标准方法:`GET`, `POST`, `PUT`, `DELETE` 等 - 通过 `http.RequestMethod` 枚举调用 2. **参数处理**: - GET 参数自动 URL 编码 - POST 数据自动 JSON 序列化 3. **错误处理**: - 自动捕获网络异常 - 验证 HTTP 状态码(200-299 视为成功) 4. **响应处理**: - 自动将响应体解析为 JSON 对象 - 原始数据可通过 `response.result` 获取 #### 五、进阶配置 ```typescript // 自定义请求示例 const customRequest = await httpRequest.request( 'https://api.example.com/upload', { method: http.RequestMethod.PUT, header: { 'Authorization': 'Bearer token', 'Custom-Header': 'value' }, connectTimeout: 30_000, // 30秒超时 usingCache: true // 启用缓存 } ); ``` > **注意事项**: > 1. 鸿蒙 NEXTHTTP 客户端**不支持服务端开发**,需通过 `TCPSocketServer` 自行实现 [^2] > 2. 使用 HTTPS 需配置网络安全策略 > 3. 文件上传需使用 `@ohos.multimedia.mediaLibrary` 模块
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值