json字符串形式的fetch请求
static HOST = "https://www.baidu.com:8002/app/";
/**
* json格式的post请求(请求方式)
* @param location 接口字段
* @param parameters 请求参数(没有传空对象"{}")
* @param succeedCallBack 返回成功回调
* @param failCallBack 返回失败回调
*/
static doPost(location, parameters, succeedCallBack, failCallBack,ref) {
let url = this.HOST + location;
let fetchOptions = {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(parameters)
};
fetch(url, fetchOptions)
.then((response) => response.json())
.then((responseText) => {
Logger.log(responseText);
succeedCallBack(responseText);
}).catch((error) =>{
failCallBack(error)
}).done();
}
/**
* json格式的get请求(请求方式)
* @param location 接口字段
* @param parameters 请求参数(没有传空对象"{}")
* @param succeedCallBack 返回成功回调
* @param failCallBack 返回失败回调
*/
static doGet(location, parameters, succeedCallBack, failCallBack,ref) {
parameters = this.getParametersString(parameters);
let url = this.HOST + location + '?' + parameters;
let fetchOptions = {
method: 'GET',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
};
fetch(url,fetchOptions)
.then((response) =>this.parseToJson(response))
.then((responseText) => {
Logger.log(responseText);
succeedCallBack(responseText);
}).catch((error) =>{
failCallBack(error);
}).done();
}
//拼接参数的方法
static getParametersString(parameters) {
let ps = null;
for (let key in parameters) {
if (ps == null) {
if (parameters[key] instanceof Object) {
ps = key + '=' + JSON.stringify(parameters[key]);
} else {
ps = key + '=' + parameters[key];
}
} else {
if (parameters[key] instanceof Object) {
ps = ps + '&' + key + '=' + JSON.stringify(parameters[key]);
} else {
ps = ps + '&' + key + '=' + parameters[key];
}
}
}
if (ps == null) {
return '';
}
return ps;
}
form 形式的fetch请求
/**
* form的post请求(请求方式)
* @param location 接口字段
* @param parameters 请求参数(没有传空对象"{}")
* @param succeedCallBack 返回成功回调
* @param failCallBack 返回失败回调
*/
static doPost(location, parameters, succeedCallBack, failCallBack,ref) {
let url = this.HOST + location;
let fetchOptions = {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'token':GlobalCatchUtil.getUserLoginToken(),
},
body: this.getParametersString(parameters)
};
fetch(url, fetchOptions)
.then((response) =>this.parseToJson(response))
.then((responseObj) => {
Logger.log('response ='+JSON.stringify(responseObj));
succeedCallBack(responseObj);
}).catch((error) =>{
failCallBack(error);
}).done();
}
//拼接参数的方法
static getParametersString(parameters) {
let ps = null;
for (let key in parameters) {
if (ps == null) {
if (parameters[key] instanceof Object) {
ps = key + '=' + JSON.stringify(parameters[key]);
} else {
ps = key + '=' + parameters[key];
}
} else {
if (parameters[key] instanceof Object) {
ps = ps + '&' + key + '=' + JSON.stringify(parameters[key]);
} else {
ps = ps + '&' + key + '=' + parameters[key];
}
}
}
if (ps == null) {
return '';
}
return ps;
}
网友评论