我们在项目中经常会用到HTTP请求来访问网络,HTTP(HTTPS)请求通常分为"GET"、"PUT"、"POST"、"DELETE",如果不指定默认为GET请求。
在项目中我们常用到的一般为GET和POST两种请求方式,针对带参数的表单提交这类的请求,我们通常会使用POST的请求方式。
为了发出HTTP请求,我们需要使用到 React Native 提供的 Fetch API 来进行实现。要从任意地址获取内容的话,只需简单地将网址作为参数传递给fetch方法即可(fetch这个词本身也就是获取的意思
GET
如果你想要通过 GET 方法去请求数据并转化成 JSON,可以通过如下代码实现:
fetch('https://facebook.github.io/react-native/movies.json')
.then((response) => response.json())
.then((responseJson) => {
return responseJson.movies;
})
.catch((error) => {
console.error(error);
});
通过上面的请求把返回的 Response 转化成 JSON Object,然后取出 JSON Object 里的 movies 字段。同时,如果发生 Error,如网络不通或访问连接错误等, 会被 .catch 。在正常的情况下,我们可以得到如下结果:
{
"title": "The Basics - Networking",
"description": "Your app fetched this from a remote endpoint!",
"movies": [
{ "title": "Star Wars", "releaseYear": "1977"},
{ "title": "Back to the Future", "releaseYear": "1985"},
{ "title": "The Matrix", "releaseYear": "1999"},
{ "title": "Inception", "releaseYear": "2010"},
{ "title": "Interstellar", "releaseYear": "2014"}
]
}
POST(一)
当然,上面是最基本的 GET 请求,Fetch还有可选的第二个参数,可以用来定制HTTP请求一些参数。你可以指定Headers参数,或是指定使用POST方法,又或是提交数据等等:Fetch API 还支持自定义 Headers,更换 Method,添加 Body 等。
let url = "http://www.yousite.com/xxxx.ashx”
let params = {"name":"admin","password":"admin"};
fetch(url, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify(params)
})
上面构建了一个基本的 POST 请求,添加了自己的 Headers:Accept和Content-Type,添加了 Body。
POST(二)
let url = "http://www.yousite.com/xxxx.ashx”;
let params = "username=admin&password=admin”;
fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
body: params,
}).then((response) => {
if (response.ok) {
return response.json();
}
}).then((json) => {
console.log(json)
}).catch((error) => {
console.error(error);
});
POST(三)推荐
通过上面两种方法,我们还有一种方式可以发送POST请求,当然这种方式也是被推荐使用的。
