utils.uts 1.9 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
/**
 * 鸿蒙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) {
DCloud-yyl's avatar
DCloud-yyl 已提交
22 23 24 25 26 27 28 29 30 31 32
    try {
        const urlObj = harmonyUrl.URL.parseURL(url);
        urlObj.params.forEach((value, key) => {
            if (needsEncoding(value)) {
                urlObj.params.set(key, value);
            }
        })
        return urlObj.toString()
    } catch (error) {
        return url
    }
DCloud-yyl's avatar
DCloud-yyl 已提交
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
}

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
}