网络请求封装
使用方式
NetUtils.get("gept/api/project/getProjectData",null,(result)=>{
console.log(result);
})
NetUtils代码
import Toast from 'react-native-simple-toast';
const BASE_URL = "http://172.27.103.192:8080/";
import {
Platform
} from 'react-native';
export default class NetUtils {
static get(url,params, callback) {
let newUrl=BASE_URL+url;
var newParams = this.getNewParams(params);
if(newParams!==null){
newUrl = BASE_URL + url + "?" + newParams;
}
console.log(newUrl);
fetch(newUrl, {
method: 'GET'
})
.then((response) => {
if (response.ok) {
return response.json();
}
})
.then((json) => {
console.log(json);
if (json.header.code === "1"||json.header.code==="success") {
callback(json);
} else {
Toast.show(json.header.message, Toast.SHORT);
}
}).catch(error => {
console.log(error);
Toast.show("netword error", Toast.SHORT);
});
};
static post(url, params, callback) {
let newUrl=BASE_URL+url;
console.log(newUrl);
var newParams = this.getNewParams(params);
fetch(newUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
},
body: newParams
})
.then((response) => {
if (response.ok) {
return response.json();
}
})
.then((json) => {
console.log(json);
if (json.header.code === "1"||json.header.code==="success") {
callback(json);
} else {
Toast.show(json.header.message, Toast.SHORT);
}
}).catch(error => {
console.log(error);
Toast.show("netword error", Toast.SHORT);
});
};
static postJson(url, jsonObj, callback) {
let newUrl=BASE_URL+url;
fetch(newUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json;charset=UTF-8'
},
body: JSON.stringify(jsonObj),
})
.then((response) => {
if (response.ok) {
return response.json();
}
})
.then((json) => {
console.log(json);
if (json.header.code === "1"||json.header.code==="success") {
callback(json);
} else {
Toast.show(json.header.message, Toast.SHORT);
}
}).catch(error => {
console.log(error);
Toast.show("netword error", Toast.SHORT);
});
};
static getNewParams(oldParams) {
let device_type=Platform.OS==='android'?"1":"2";
let userid="";
let token="";
if(oldParams!==null){
newParams = oldParams+"&sysid=emc&device_type="+device_type+"userid="+userid+"token"+token;
}else{
newParams="sysid=emc&device_type="+device_type+"userid="+userid+"token="+token;
}
return newParams;
};
}