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

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请求主流的分getpost方式. 都可以在 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之旅有帮助。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值