react native http request
https://reactnative.cn/docs/network/
https://github.com/axios/axios
示例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 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 59 60 61 62 63 64 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 | var api = { API_ROOT: "https://www.xxx.com" , API_TOKEN: "" }; export function setToken(token) { console.log( 'set token: ' + token); api.API_TOKEN = token; } export function getToken(token) { // console.log('set token: ' + token); return api.API_TOKEN; } export function getRoot() { // console.log('set token: ' + token); return api.API_ROOT; } export function UserInfo(id, params, callback) { return getRequest(`/users/${id}`, params, callback); } export function HotSongList( params, callback) { return getRequest(`/api/songList/hot`, params, callback); } export function GetMusicList( params, callback) { return getRequest(`/api/songList`, params, callback); } export function SearchMusicInfo( params, callback) { return getRequest(`/api/search`, params, callback); } function getRequest(url, params) { var curl = getUrl(url, params); console.log( 'get request:' + curl); var context = { headers: { 'Accept' : 'application/json' , 'Content-Type' : 'application/json' , "Authorization" : "Bearer " + api.API_TOKEN }, method: 'GET' }; return new Promise( function (resolve, reject) { fetch(curl, context) .then(response => { var status = response.status; if (status >= 200 && status <= 204) { // 请求成功 return response.text(); } else if (status >= 400 && status <= 404) { var msg = JSON.parse(response._bodyText).msg; reject(msg); // 权限问题,直接跳转到登录 const routers = app.nav.getCurrentRoutes(); if (routers.length > 0 && routers[0].name != "Login" ) { // api.API_TOKEN = ''; // app.nav.resetTo({name: 'Login'}); } } else { reject( "未知错误!" + response._bodyText); } return null ; }) .then(body => { if (body) { resolve(JSON.parse(body)); } }) . catch (error => { reject(error); }); }); } function post(url, data, callback){ console.log(data); let turl = getUrl(url, null ); console.log( 'post request:' + turl); let context = { method: 'POST' , body: JSON.stringify(data), headers: { 'Accept' : 'application/json' , 'Content-Type' : 'application/json' , "Authorization" : "Bearer " + api.API_TOKEN } }; request(turl,callback,context); } function request(url,callback,context){ fetch(url, context). then((response) => { const status = response.status; if (status === 401) { setToken( '' ); } if (status >= 200 && status <= 204) { // 如果是正常返回,往下传数据 return response.text(); } else if (status >= 400 && status < 404) { response.text().then((text)=>{ const msg = JSON.parse(text).msg; callback( false , msg); }); } else { callback( false , "未知错误" ); } return null ; }). then((body) => { if (body) { callback( true , JSON.parse(body)); } }). catch ((error) => { callback( false , JSON.stringify(error)); }); } function getUrl(url,params){ let ret = api.API_ROOT + url; let paramstr= paramsStr(params); if (paramstr.length>0){ ret = ret + '?' + paramstr; } // console.log(ret); return ret; } function paramsStr(params){ let paramstr = '' ; let param = params || {}; if (param){ let i = 0; for ( let p in param) { if (i>0){ paramstr += '&' ; } paramstr += p + '=' + encodeURI(params[p]); i += 1; }; } return paramstr; } export function getUrls(url,params){ let ret = api.API_ROOT + url; let paramstr= paramsStr(params); if (paramstr.length>0){ ret = ret + '?' + paramstr; } // console.log(ret); return ret; } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 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 59 60 61 62 63 64 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 | import {Component} from 'react' /** * fetch 网络请求的header,可自定义header 内容 * @type {{Accept: string, Content-Type: string, accessToken: *}} */ let header = { 'Accept' : 'application/json' , 'Content-Type' : 'application/json' , } /** * GET 请求时,拼接请求URL * @param url 请求URL * @param params 请求参数 * @returns {*} */ const handleUrl = url => params => { if (params) { let paramsArray = [] Object.keys(params).forEach(key => paramsArray.push(key + '=' + encodeURIComponent(params[key]))) if (url.search(/\?/) === -1) { typeof (params) === 'object' ? url += '?' + paramsArray.join( '&' ) : url } else { url += '&' + paramsArray.join( '&' ) } } return url } /** * fetch 网络请求超时处理 * @param original_promise 原始的fetch * @param timeout 超时时间 10s * @returns {Promise.<*>} */ const request = (original_fetch, timeout = 10000) => { let timeoutBlock = () => {} let timeout_promise = new Promise((resolve, reject) => { timeoutBlock = () => { reject( 'request timeout' ); } }) // Promise.race(iterable)方法返回一个promise // 这个promise在iterable中的任意一个promise被解决或拒绝后,立刻以相同的解决值被解决或以相同的拒绝原因被拒绝。 let abortable_promise = Promise.race([ original_fetch, timeout_promise ]) setTimeout(() => { timeoutBlock() }, timeout) return abortable_promise } export default class HttpClient extends Component { /** * 基于fetch 封装的GET 网络请求 * @param url 请求URL * @param params 请求参数 * @returns {Promise} */ static get = (url, params = {}) => { return request(fetch(handleUrl(url)(params), { method: 'GET' , headers: header })).then(response => { if (response.ok) { return response.json() } else { alert(response) } }).then(response => { // response.code:是与服务器端约定code:200表示请求成功,非200表示请求失败,message:请求失败内容 if (response) { return response } else { // 非 200,错误处理 return response } }). catch (error => { alert(error) }) } /** * 基于fetch 的 POST 请求 * @param url 请求的URL * @param params 请求参数 * @returns {Promise} */ static post = (url, params = {}) => { return request(fetch(url, { method: 'POST' , headers: header, body: JSON.stringify(params) })).then(response => { if (response.ok) { return response.json() } else { alert( '服务器繁忙,请稍后再试;\r\nCode:' + response.status) } }).then(response => { // response.code:是与服务器端约定code:200表示请求成功,非200表示请求失败,message:请求失败内容 if (response && response.code === 200) { return response } else { return response } }). catch (error => { alert(error) }) } } |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 一文读懂知识蒸馏
· 终于写完轮子一部分:tcp代理 了,记录一下