utils.uts 2.0 KB
Newer Older
DCloud-yyl's avatar
DCloud-yyl 已提交
1
import harmonyUrl from '@ohos.url'
DCloud-yyl's avatar
DCloud-yyl 已提交
2 3 4
import { http } from '@kit.NetworkKit'
import { Certificate } from '../../interface.uts'
import { getRealPath } from '@dcloudio/uni-runtime'
DCloud-yyl's avatar
DCloud-yyl 已提交
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
/**
 * 鸿蒙url内包含中文时处理有问题
 * 例如 /code/version/11?subject=中文测试 在部分服务器上会收到 /code/version/11?subject=道德与æ³
 * 如下看起来很怪异的代码仅仅是为了绕过此Bug,待鸿蒙修复后可删除
 */

function needsEncoding(str: string) {
    const decoded = decodeURIComponent(str);
    if (decoded !== str) {
        if (encodeURIComponent(decoded) === str) {
            return false;
        }
    }
    return encodeURIComponent(decoded) !== decoded;
}

export function parseUrl(url: string) {
    const urlObj = harmonyUrl.URL.parseURL(url);
    urlObj.params.forEach((value, key) => {
        if (needsEncoding(value)) {
            urlObj.params.set(key, value);
        }
    })
    return urlObj.toString()
}
DCloud-yyl's avatar
DCloud-yyl 已提交
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68

interface IUniNetworkMPUserAgent {
    fullUserAgent: string
}

export interface IUniNetworkMP {
    on: Function
    off: Function
    userAgent: IUniNetworkMPUserAgent
}

export const certificates: Certificate[] = []

function getCertType(certPath: string): http.CertType {
    const certExt = certPath.split('.').pop()
    switch (certExt) {
        case 'p12':
            return http.CertType.P12
        case 'pem':
            return http.CertType.PEM
        default:
            return http.CertType.PEM
    }
}

export function getClientCertificate(url: string): http.ClientCert | undefined {
    if (certificates.length === 0) return undefined
    const urlObj = harmonyUrl.URL.parseURL(url);
    const cert = certificates.find((certificate) => certificate.host === urlObj.host)
    if (cert) {
        return {
            certType: getCertType(cert.client!),
            certPath: getRealPath(cert.client!),
            keyPath: cert.keyPath ?? '',
            keyPassword: cert.clientPassword
        } as http.ClientCert
    }
    return undefined
}