export class HttpUtil {

    static get(url: string, callback: (statusCode: number, resp: object | null) => any) {
        let xhr = new XMLHttpRequest();
        xhr.timeout = 2000;
        xhr.open("GET", url);
        xhr.onreadystatechange = () => {
            if (xhr.readyState == 4 && xhr.status >= 200 && xhr.status < 400) {
                let resp = null;
                try {
                    if (xhr.responseText != "") {
                        resp = JSON.parse(xhr.responseText);
                    }
                } catch (e) {
                }
                callback && callback(1, resp);
            }
        };
        xhr.onerror = () => {
            callback && callback(0, null);
        };
        xhr.ontimeout = () => {
            callback && callback(0, null);
        };
        xhr.send();
        return xhr;
    }

    static post(url: string, callback: (statusCode: boolean, resp: any | null) => any, data: object | string | null) {
        let xhr = new XMLHttpRequest();
        xhr.timeout = 2000;
        xhr.open("POST", url, true);
        xhr.setRequestHeader("Content-Type", "text/plain;charset=UTF-8");
        xhr.onreadystatechange = () => {
            if (xhr.readyState == 4 && xhr.status >= 200 && xhr.status < 400) {
                let resp = null;
                try {
                    if (xhr.responseText != "") {
                        resp = JSON.parse(xhr.responseText);
                    }
                } catch (e) {
                }
                callback && callback(true, resp);
            }
        };
        xhr.onerror = (mgs) => {
            console.log('网络错误');
            callback && callback(false, null);
        };
        xhr.ontimeout = (mgs) => {
            console.log('网络超时');
            callback && callback(false, null);
        };
        if (data) {
            let text = typeof (data) == "string" ? data : JSON.stringify(data);
            xhr.send(text);
            return xhr;
        }
        xhr.send();
        return xhr;
    }
}
