index.uts 6.2 KB
Newer Older
1 2
import { Request, RequestOptions, RequestSuccess, RequestFail, RequestTask } from './interface';
import { NetworkManager, NetworkRequestListener } from './network/NetworkManager.uts'
DCloud-yyl's avatar
DCloud-yyl 已提交
3 4
import { Data, HTTPURLResponse, NSError, NSNumber , ComparisonResult , RunLoop , Thread } from 'Foundation';
import { StatusCode } from './network/StatusCode.uts';
5 6 7 8 9

class SimpleNetworkListener extends NetworkRequestListener {
	private param : RequestOptions | null = null;
	private headers : Map<string, any> | null = null;
	private received : number = 0;
DCloud-yyl's avatar
DCloud-yyl 已提交
10
	private data : Data = new Data();
11
	constructor(param : RequestOptions) {
DCloud-yyl's avatar
DCloud-yyl 已提交
12
		this.param = param;
13 14 15 16 17 18 19 20 21 22
		super();
	}

	public override onStart() : void {
	}

	public override onHeadersReceived(statusCode : number, headers : Map<string, any>) : void {
		this.headers = headers;
	}
	public override onDataReceived(data : Data) : void {
DCloud-yyl's avatar
DCloud-yyl 已提交
23
		this.received += Number.from(data.count);
24 25 26 27 28 29 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
		this.data.append(data);
	}

	public override onFinished(response : HTTPURLResponse) : void {
		try {
			let headers = response.allHeaderFields as Map<string, any>;
			let kParam = this.param;
			let result = {};
			result['statusCode'] = response.statusCode;
			result['statusText'] = StatusCode.getStatus(new String(response.statusCode));
			if (headers != null) {
				result['header'] = headers;
			}
			let strData = this.readStringFromData(this.data, response.textEncodingName);


			let type = kParam?.responseType != null ? kParam?.responseType : kParam?.dataType;

			if (type == null && headers != null) {
				
				for (entry in headers){
					let key = entry.key;
					if (key.caseInsensitiveCompare("Content-Type") == ComparisonResult.orderedSame) {
						type = headers[key] as string;
					}
				}
			}
			

			result['data'] = this.parseData(this.data, strData, type);

			let tmp : RequestSuccess = {
				data: result['data']!,
				statusCode: (new NSNumber(value = response.statusCode)),
				header: result['header'] ?? "",
DCloud-yyl's avatar
DCloud-yyl 已提交
59
				cookies: this.parseCookie(this.headers)
60 61 62 63
			};
			let success = kParam?.success;
			let complete = kParam?.complete;
			success?.(tmp);
DCloud-yyl's avatar
DCloud-yyl 已提交
64
			complete?.(tmp);
65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167
		} catch (e) {
		}
	}

	public override onFail(error : NSError) : void {

		let kParam = this.param;
		let result = {};
		let code = (error as NSError).code;
		// result['data'] = error.localizedDescription + "(" + new String(code) + ")";
		// result['errorMsg'] = error.localizedDescription + "(" + new String(code) + ")";
		// result['statusText'] = StatusCode.getStatus(new String(code) + "");
		// if (this.headers != null) {
		// 	result['header'] = this.headers;
		// }

		let errCode = code;
		let errMsg = error.localizedDescription;
		if (code == -1001) {
			errCode = 5;
		} else if (code == -1004) {
			errCode = 1000;
		} else if (code == -1009) {
			errCode = 600003;
		} else if (code == -1000 || code == -1002 || code == -1003) {
			errMsg = 'ERR_INVALID_REQUEST';
		}


		// let failResult : RequestFail = {
		// 	errSubject: "uni-request",
		// 	errMsg: errMsg,
		// 	errCode: errCode,
		// };
		let failResult : RequestFail = new UniError("uni-request", Number.from(errCode), errMsg);

		let fail = kParam?.fail;
		let complete = kParam?.complete;
		fail?.(failResult);
		complete?.(failResult);
	}


	private readStringFromData(data : Data, type : string | null) : string | null {
		let result : string | null = null;
		let finalType = type;
		if (finalType == null || finalType!.length == 0) {
			finalType = "utf-8";
		}

		let cfEncoding = CFStringConvertIANACharSetNameToEncoding(finalType as CFString);
		if (cfEncoding != kCFStringEncodingInvalidId) {
			let stringEncoding = CFStringConvertEncodingToNSStringEncoding(cfEncoding);
			let encode = new String.Encoding(rawValue = stringEncoding);
			result = new String(data = data, encoding = encode);
		}
		return result;
	}

	private parseData(data : Data | null, dataStr : string | null, type : string | null) : any | null {
		if (type != null && type!.contains("json")) {
			if (dataStr == null || dataStr!.length == 0) {
				return {};
			}
			return this.parseJson(dataStr!);
		} else if (type == 'jsonp') {
			if (dataStr == null || dataStr!.length == 0) {
				return {};
			}
			let start = dataStr!.indexOf('(');
			let end = dataStr!.indexOf(')');
			if (start == 0 || start >= end) {
				return {};
			}
			start += 1;
			let tmp = dataStr!.slice(start, end);
			return this.parseJson(tmp);
		} else {
			//dataStr如果解码失败是空的时候,还需要继续尝试解码。极端情况,服务器不是utf8的,所以字符解码会出现乱码,所以特殊处理一下非utf8的字符。
			if (data == null) {
				return data;
			}

			let currentStr : string | null = dataStr;
			//todo 等uts支持swift文件混编的时候,再进行处理。
			// if (currentStr == null) {
			// 	let data = cleanUTF8(data);
			// 	if (data != null) {
			// 		currentStr = new String(data = data, encoding = String.Encoding.utf8);
			// 	}
			// }

			if (currentStr == null) {
				currentStr = new String(data = data!, encoding = String.Encoding.ascii);
			}

			return currentStr;
		}
	}


	private parseJson(str : string) : any | null{
		return JSON.parse(str);
DCloud-yyl's avatar
DCloud-yyl 已提交
168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196
	}
	
	private parseCookie(header : Map<string, any> | null) : string[] {
		if (header == null) {
			return []
		}
		let cookiesStr = header!.get('Set-Cookie') as string | null
		if (cookiesStr == null) {
			cookiesStr = header!.get('set-cookie') as string | null
		}
		if (cookiesStr == null) {
			return []
		}
		let cookiesArr = new Array<string>()
		if (cookiesStr!.charAt(0) == "[" && cookiesStr!.charAt(cookiesStr!.length - 1) == "]") {
			cookiesStr = cookiesStr!.slice(1, -1)
		}
	
		const handleCookiesArr = cookiesStr!.split(';')
		for (let i = 0; i < handleCookiesArr.length; i++) {
			if (handleCookiesArr[i].indexOf('Expires=') != -1 || handleCookiesArr[i].indexOf('expires=') != -1) {
				cookiesArr.push(handleCookiesArr[i].replace(',', ''))
			} else {
				cookiesArr.push(handleCookiesArr[i])
			}
		}
		cookiesArr = cookiesArr.join(';').split(',')
	
		return cookiesArr
197 198 199
	}
}

DCloud-yyl's avatar
DCloud-yyl 已提交
200
export const request : Request = (param : RequestOptions) : RequestTask => {
201 202
	return NetworkManager.getInstance().request(param, new SimpleNetworkListener(param));
}