this.fetch是一个方法,用于发起http请求。
fetch方法模拟浏览器环境中Fetch API,但要简化一些。fetch方法调用java.net.HttpURLConnection类发起请求。
Syntax
const resPromise = fetch(url, options);
Parameters
-
url
String
要获取资源的 URL。
-
options
Object
一个配置项对象,包括对请求的设置。可选的参数有:method, headers, body
Returns
-
Promise
resolve 时回传 Response 对象。
Examples
样例一: 发起一个GET请求,获取响应文本:
fetch('http://hostname/resource').then((res)=>{
return res.text();
}).then((text)=>{
console.log(`响应的文本信息是:${text}`);
});
样例二一: 发起get请求。获取json数据,并在header中附带认证信息。
fetch('http://hostname/resource', {
headers: {
"Authorization": "xxxxxxxxxxxxx"
}
}).then((res)=>{
return res.json();
}).then((json)=>{
console.log(`响应的json对象是:${JSON.stringify(json, null, '\t')}`);
});
样例三: 发起一个POST请求,获取响应json:
fetch('http://hostname/resource', {
method: 'post',
body: '{"postData": "this is post data"}',
headers: {
"Content-Type": "application/json; charset=UTF-8"
}
}).then((res)=>{
return res.json();
}).then((json)=>{
console.log(`响应的json对象是:${JSON.stringify(json, null, '\t')}`);
});
样例四: 使用res.blob()方法获取Response流(java.io.ByteArrayInputStream);或使用res.arrayBuffer()方法获取Response的ArrayBuffer对象
fetch('http://hostname/resource').then((res)=>{
return res.blob();
}).then((blob)=>{
//获取到 blob,实际上是一个(java.io.ByteArrayInputStream)对象
});
fetch('http://hostname/resource').then((res)=>{
return res.arrayBuffer();
}).then((arrayBuffer)=>{
//获取到 arrayBuffer对象
});
样例五: 错误处理。如果遇到网络错误,fetch将会reject,而如果是服务器响应的错误,如:500, 415等不是一个网络故障,所以想要精确的判断 fetch() 是否成功,需要包含 promise resolved 的情况下,再判断 res.ok 是否为 true。
fetch('http://hostname/resource').then((res)=>{
if (!res.ok){
throw new Error("response was not OK");
}
return res.json();
}).then((json)=>{
console.log(`响应的json对象是:${JSON.stringify(json, null, '\t')}`);
}).catch((e)=>{
//处理请求错误
});
样例六: 获取响应的信息。
fetch('http://hostname/resource').then((res)=>{
res.ok //请求是否成功
res.status //请求响应的状态码
res.statusText //请求响应的状态文本
res.headers //响应头
res.error //java.net.HttpURLConnection的错误流
res.connection //java.net.HttpURLConnection对象
res.text() //响应内容文本
res.json() //响应内容json对象
res.blob() //响应内容Response流(java.io.ByteArrayInputStream)
res.arrayBuffer() //响应内容Response的ArrayBuffer对象
});
样例七: 使用await。
try{
const res = await fetch('http://hostname/resource');
if (res.ok){
const json = await res.json();
//获取到json对象
}else{
log.error(`请求出现错误:${res.statusText}`);
}
}catch(e){
log.error(`请求出现错误:${e.message}`);
}