开天辟地 HarmonyOS(鸿蒙) - 网络: http

源码 https://github.com/webabcd/HarmonyDemo
作者 webabcd

开天辟地 HarmonyOS(鸿蒙) - 网络: http

示例如下:

pages\network\HttpDemo.ets

/*
 * http 请求
 *
 * 需要在 src/main/module.json5 中添加网络权限,类似如下
 * {
 *   "module": {
 *     "requestPermissions":[
 *       {
 *         "name" : "ohos.permission.INTERNET", // 使用 Internet 网络的权限
 *         "reason": "$string:hello_webabcd", // 申请此权限的原因
 *         "usedScene": {
 *           "abilities": [ ],
 *           "when":"always" // inuse(使用时允许使用此权限),always(始终允许使用此权限)
 *         }
 *       },
 *     ]
 *   }
 * }
 */

import { TitleBar } from '../TitleBar';
import { http } from '@kit.NetworkKit';
import { BusinessError } from '@kit.BasicServicesKit';

@Entry
@Component
struct HttpDemo {

  build() {
    Column() {
      TitleBar()
      Tabs() {
        TabContent() { MySample1() }.tabBar('get/post').align(Alignment.Top)
      }
      .scrollable(true)
      .barMode(BarMode.Scrollable)
      .layoutWeight(1)
    }
  }
}

@Component
struct MySample1 {

  @State message: string = ""

  /*
   * HttpRequest - 用于 http 请求
   *   http.createHttp() - 创建一个 HttpRequest 实例
   *   on(), off() - 监听指定事件,取消监听指定事件
   *     headersReceive - 收到响应 header 后的事件
   *   request() - 开始 http 请求
   *     url - url
   *     options - 选项(一个 HttpRequestOptions 对象)
   *       header - 请求头
   *       method - 请求方法(RequestMethod 枚举)
   *         OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
   *       expectDataType - 返回数据的类型(HttpDataType 枚举)
   *         STRING, OBJECT, ARRAY_BUFFER
   *       connectTimeout - 连接的超时时间(单位:毫秒)
   *       readTimeout - 读取的超时时间(单位:毫秒)
   *       extraData - post 的数据
   *     callback - 回调(回调参数是一个 BusinessError 对象和一个 HttpResponse 对象)
   *       result - 响应的结果
   *       responseCode - 响应的 http 状态码
   *   destroy() - 中断并销毁(注:请求完毕后需要调用此方法释放资源)
   */

  async get_sample() {
    this.message = ""
    let httpRequest = http.createHttp()

    httpRequest.on('headersReceive', (header) => {
      this.message += `header: ${JSON.stringify(header)}\n`
    });

    httpRequest.request(
      "http://192.168.8.197:8001/api?k1=v1&k2=v2",
      {
        header: {
          'custom-header1': 'abc'
        },
        method: http.RequestMethod.GET,
        expectDataType: http.HttpDataType.STRING,
        connectTimeout: 60_000,
        readTimeout: 60_000,
      },
      (err: BusinessError, data: http.HttpResponse) => {
        if (!err) {
          this.message += `result: ${JSON.stringify(data.result)}\n`
          this.message += `response code: ${data.responseCode}\n`
        } else {
          this.message += `error: ${JSON.stringify(err)}\n`
        }
        httpRequest.off('headersReceive')
        httpRequest.destroy()
      }
    );
  }

  async post_sample() {
    interface IPerson {
      name: string
      age: number
    }
    const person: IPerson = {
      name: "webabcd",
      age: 44,
    }
    const postData = JSON.stringify(person)

    this.message = ""
    let httpRequest = http.createHttp()

    httpRequest.on('headersReceive', (header) => {
      this.message += `header: ${JSON.stringify(header)}\n`
    });

    httpRequest.request(
      "http://192.168.8.197:8001/api?k1=v1&k2=v2",
      {
        header: {
          'Content-Type': 'application/json',
          'custom-header1': 'abc'
        },
        method: http.RequestMethod.POST,
        expectDataType: http.HttpDataType.STRING,
        connectTimeout: 60_000,
        readTimeout: 60_000,
        extraData: postData,
      },
      (err: BusinessError, data: http.HttpResponse) => {
        if (!err) {
          this.message += `result: ${JSON.stringify(data.result)}\n`
          this.message += `response code: ${data.responseCode}\n`
        } else {
          this.message += `error: ${JSON.stringify(err)}\n`
        }
        httpRequest.off('headersReceive')
        httpRequest.destroy()
      }
    );
  }

  build() {
    Column({space:10}) {
      Button("get").onClick(async () => {
        await this.get_sample()
      })

      Button("post").onClick(async () => {
        await this.post_sample()
      })

      Text(this.message)
    }
  }
}

\webapi\webapi\webserver.py

from aiohttp import web
import json

def setup_routes(app):
    app.router.add_route('*', '/api', httpapi)

async def launch():
    app = web.Application()
    runner = web.AppRunner(app)
    setup_routes(app)
    await runner.setup()
    site = web.TCPSite(runner, '0.0.0.0', 8001)
    await site.start()


async def httpapi(request):
    k1 = request.query.get('k1', '')
    k2 = request.query.get('k2', '')
    
    h1 = request.headers.get('custom-header1', '')
        
    data = await request.content.read()
    postData = data.decode()
        
    result = f"method:{request.method}, k1:{k1}, k2:{k2}, h1:{h1}, postData:{postData}"

    return web.Response(text=result)

    try:
        db = sqlite.Connect(config.db_path)
        taskId = dict["ID"]
        priority = dict["Priority"]

        source_url = dict["Source"]
        source_language = ''
        target_language = dict["Language"]
        if source_language == '' or source_language == 'auto':
            ...
        elif source_language not in config.settings_nllb_language:
            raise MyException(301, f"语言 {source_language} 不支持,目前支持的语言有:{','.join(config.settings_nllb_language.keys())}")
        if target_language == '':
            ...
        else:
            unsupported_language = set(target_language.split(',')).difference(set(config.settings_nllb_language.keys()))
            if len(unsupported_language) > 0:
                raise MyException(301, f"语言 {','.join(unsupported_language)} 不支持,目前支持的语言有:{','.join(config.settings_nllb_language.keys())}")

        # 先删除同 taskid 的数据,因为更新逻辑是根据 id 更新的,所以运行中的逻辑完成后是找不到可更新的数据的,所以不会和后面新加进来的同 taskid 数据发生冲突
        # db.table('task').delete(f'where taskid=\'{taskId}\'')

        task_status = await get_task_status(dict, resetIfFailed=True)
        if task_status[0] == 102: # 无此任务
            ...
        else:
            return task_status
        
        step_list = config.task_step_list_default
        if source_url.endswith(".srt"):
            step_list = config.task_step_list_translate

        db.table('task').add({
            'id': common.get_uuid(), 
            'taskid': taskId, 
            'priority': str(priority), 
            'data': json.dumps(dict), 
            'ext': "",
            'step': step_list[0], 
            'steplist': ",".join(step_list), 
            'status': 0, 
            'createtime': common.sqlite_time2str(common.get_time()), 
            'updatetime': common.sqlite_time2str(common.get_time()), 
            'log': ""
        })
        return 0, "ok"
    #except sqlite3.IntegrityError as ex:
        #raise MyException(101, "任务正在排队")
    except Exception as ex:
        raise ex
    finally:
        db.close()

源码 https://github.com/webabcd/HarmonyDemo
作者 webabcd

posted @   webabcd  阅读(8)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· 没有源码,如何修改代码逻辑?
· PowerShell开发游戏 · 打蜜蜂
· 在鹅厂做java开发是什么体验
· WPF到Web的无缝过渡:英雄联盟客户端的OpenSilver迁移实战
历史上的今天:
2007-02-21 温故知新ASP.NET 2.0(C#)(6) - Membership&RoleManager(成员资格和角色管理)
点击右上角即可分享
微信分享提示