您的位置:首页 > 理论基础 > 计算机网络

react-native 网络请求,超时总结

2017-05-24 17:04 369 查看

react-native 网络请求总结

参考:

[1] http://blog.csdn.net/u010046908/article/details/50916511

[2] https://github.com/facebook/react-native/issues/2556

[3] https://github.com/robinpowered/react-native-fetch-polyfill

react-native的网络请求,总会遇到这样,或者那样的问题。这里我根据网上的资源,和自己的实践经验,总结下遇到的问题。

1. 使用哪种工具请求网络?

目前react-native推荐的是
fetch,XHttpRequest
等工具。我自己用的
fetch
方法。

2. 如何用fetch请求http?

http请求主流的分
get
post
方式. 都可以在
fetch
方法中设置.

2.1 get方式请求

static get(url, callback) {
fetch(url)
.then((response) => response.text())
.then((responseText) => {
callback(JSON.parse(responseText));
}).done();
}


代码中对返回的response对象,直接调用
Json.parse()
方法可以解析。也可以调用
response.tojson()
方法。

2.2 post请求

这里,我直接采用参考文章写的一个
NetUtil.js
工具类了,不过我们需要了解:请求时,我们可以设置
响应的HTTP内容类型
ContentType
. 这个值,可以设置header的类型:
application/json
,
application/x-www-form-urlencoded
等(其实还有很多)。
前者表示参数是json类型数据,后者表示参数是表单类型数据


'use strict';
import React, {
Component,
} from 'react-native';

class NetUitl extends React.Component {

//post请求
/**
*url :请求地址
*data:参数
*callback:回调函数
*/
static  postForm(url, data, callback) {
var fetchOptions = {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded'
},
body:'data='+data+''//这里我参数只有一个data,大家可以还有更多的参数
};

fetch(url, fetchOptions)
.then((response) => response.json())
.then((responseData) => {
// 这里responseData就是一个可以用的json对象了。
callback(responseData);
}).catch(function(error) {
         callback(error, -1);
}
}

/**
*url :请求地址
*data:参数(Json对象)
*callback:回调函数
*/
static postJson (url, data, callback) {
var fetchOptions = {
method: 'POST',
headers: {
'Accept': 'application/json',
//json形式
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
};

fetch(url, fetchOptions)
.then((response) => response.json())
.then((responseData) => {
// 这里responseData就是一个可以用的json对象了。
callback(responseData);
}).catch(function(error) {
        callback(error, -1);
}
}
}

module.exports = NetUitl;


3. 调用方式如下:

get的调用方法

NetUtil.get("http://v.juhe.cn/weather/index?format="+format+"&key="+key+"&cityname="+cityname, function  (result) {
// process result
})


2.3 postJson的调用

let data={'username':'123','password':'123456','token':'HSHSIHIFAUINNSNAFKSKJFNKFKFNFNFNK'};
NetUitl.postJson(url,,function (result){
// process result a json object
});


2.4 postForm的调用

let url = Global.LOGIN;
let formData = new FormData();
formData.append("id", id);
formData.append("username", username);
formData.put("
NetUitl.postForm(url,sx,function (result){
// process result
});


超时怎么办?

目前也没有很好的办法解决超时,看网上很多方案都不可靠,主流的方式是抛弃这次http请求。用setTimeout() 方法,抛弃这次请求。我看到另外一种,引入一个[polyfill的文件]https://github.com/robinpowered/react-native-fetch-polyfill/blob/master/fetch-polyfill.js, 然后在自己的网络请求方法里,采用它定义的fetch方法,就可以设置
timeout
参数。亲测有效。

这是我自己的
HttpUtils.js
工具类:

HttpUtils.js

// 引入polyfill 解决不能设置超时的问题,直接把这个js文件拷到当前目录。
// https://github.com/robinpowered/react-native-fetch-polyfill 
import fetch from './fetch-polyfill';

console.warn("fetch url: " + url);
getData(url, callback) {

    fetch(url, {
method: 'GET',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
timeout: 20 * 1000
})
.then((response) => response.json())
.then((responseData) => {

console.warn("response code:" + responseData.code)
if(responseData.code === "C0000"
|| responseData.code === "1000"
|| responseData.code === 1000) {

console.warn("response:" + responseData.data);
callback(responseData.data, 0);
} else {
callback(responseData, -1);
}
}).catch(error => {

// an error when the request fails, such as during a timeout
callback(null, -1);
});
}
}

module.exports = {
getData
}


使用方法:

let url = getUrls() + '&id=' + id;

SelfHttp.getData(url, "", (data, code) => {

  console.warn("get data ....11111");
if(code === 0) {
// 处理data对象,取决你返回的json格式
} else {
// 显示错误界面
}
}


希望对你的react-native之旅有帮助。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  网络 react-native 超时