cocos js post FormData

只是实现了文本形式的转换,

export class TestFormData {
    private _boundary_key: string = 'testformdata';
    private _boundary: string;
    private _end_boundary: string;
    private _result: string;

    constructor() {
        this._boundary = '--' + this._boundary_key;
        this._end_boundary = this._boundary + '--';
        this._result = "";
    }

    public append(key: string, value: string) {
        this._result += this._boundary + '\r\n';
        this._result += 'Content-Disposition: form-data; name="' + key + '"' + '\r\n\r\n';
        this._result += value + '\r\n';
    }

    public get arrayBuffer(): ArrayBuffer {
        this._result += '\r\n' + this._end_boundary;
        let charArr: Array<any> = [];

        for (var i = 0; i < this._result.length; i++) { // 取出文本的charCode(10进制)
            charArr.push(this._result.charCodeAt(i));
        }

        let array: Uint8Array = new Uint8Array(charArr);
        return array.buffer;
    }
}
//这是一个简单的板栗
//var formData = new TestFormData();
//formData.append('accountId', '123');
//var xhr = cc.loader.getXMLHttpRequest();
//xhr.timeout = 3000;
//xhr.open('POST', 'http://xxxxxx', true);

//记得在头部带上boundary,这里注意一定要和类里面的 _boundary_key 保持一致
//xhr.setRequestHeader('Content-Type', 'multipart/form-data; boundary=testformdata');

//xhr.onload = function (e) {
//    if (xhr.readyState === 4 && (xhr.status >= 200 && xhr.status < 300)) {
//        console.log("xhr.responseText::", xhr.responseText)
//    }
//};
 ArrayBuffer
//xhr.send(formData.arrayBuffer);

用到了cocos中的是

postFormData: function (path, data, handler, extraUrl, errorHandler, isParse = true) {
        var xhr = cc.loader.getXMLHttpRequest();
        xhr.timeout = 15000;
        if (extraUrl == null) {
            extraUrl = this.url;
        }
        var requestURL = extraUrl + path;
        var method = "POST";
        console.log("RequestURL:" + requestURL, method);
        xhr.open(method, requestURL, true);
        // if (cc.sys.isNative) {
        //     xhr.setRequestHeader("Accept-Encoding", "text/html;charset=UTF-8");
        // } else {
        xhr.setRequestHeader("Content-Type", "multipart/form-data; boundary=testformdata");
        // }
        if (isParse) {
            xhr.onreadystatechange = function () {
                if (xhr.readyState === 4 && xhr.status == 200) {
                    console.log("http res(" + xhr.responseText.length + "):" + xhr.responseText);
                    let xhrTxt = xhr.responseText;
                    let firstCode = xhrTxt.charCodeAt(0);
                    if (firstCode < 0x20 || firstCode > 0x7f) {
                        console.log('response error 0:' + firstCode);
                        xhrTxt = xhrTxt.substring(1); // 去除第一个字符
                        console.log('response:' + xhrTxt);
                    }
                    var ret = JSON.parse(xhrTxt);
                    if (handler) {
                        handler(ret);
                    }
                }
            };
        } else {
            xhr.onreadystatechange = function () {
                if (xhr.readyState === 4 && xhr.status == 200) {
                    console.log("http res(" + xhr.response.length + "):", xhr.response);
                    if (handler) {
                        //直接输入字节流
                        handler(xhr.response);
                    }
                }
            };
        }
        xhr.onerror = function () {
            cc.log("请求超时:", requestURL, this.message);
            if (errorHandler) {
                errorHandler("请求超时:" + requestURL);
            }
        }
        xhr.ontimeout = function (e) {
            cc.log("ontimeout 请求超时:", requestURL, this.message);
            // XMLHttpRequest 超时。在此做某事。
            if (errorHandler) {
                errorHandler("请求超时:" + requestURL);
            }
        };
        // xhr.onload = function () {
        //     cc.log("onload :", xhr.status);
        //     //如果请求成功
        //     if (xhr.status == 200) {
        //         //do successCallback
        //     }
        // }
        xhr.send(this.getFormData(data));
        return xhr;
    },
    
    getFormData: function (data) {
        var boundary = '--testformdata';
        var endBoundary = boundary + '--';
        var result = "";
        var str = "?";
        for (var key in data) {
            result += boundary + '\r\n';
            result += 'Content-Disposition: form-data; name="' + key + '"' + '\r\n\r\n';
            result += data[key] + '\r\n';
        }
        result += '\r\n' + endBoundary;

        let charArr = [];

        for (var i = 0; i < result.length; i++) { // 取出文本的charCode(10进制)
            charArr.push(result.charCodeAt(i));
        }
        let array = new Uint8Array(charArr);
        return array.buffer;
    },

调用:

        cc.http.postFormData(
            'order/pay',
            {
                token: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE2Mjk5Njg3NDgsInVpZCI6IjEwMDA2In0.b_I94Ci1Nt9Xoproq4V_talWHTYz5Vl44Igotpax1vc',
                iostoken: 'hello',
            },
        );
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值