【ReactNative】网络请求

React Native中使用Fetch获取网络请求, 可以定义各种请求参数. 也可以使用XMLHttpRequest, 或其他三方库. 支持WebSocket, 使用很方便.


注意: iOS9以上都是默认https(以下使用的都是http), 所以在info.plist中添加:

1
2
3
4
5
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>

Fetch使用

自定义详细参数

1
2
3
4
5
6
7
8
9
10
11
12
//POST 增加一个user
fetch('http://localhost:3000/users',{
method:'POST',
headers:{
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body:JSON.stringify({
name:'xuneng',
age:'123'
})
})

返回的数据处理(Promise,异步)

1
2
3
4
5
6
7
8
9
10
11
12
//GET 获取所有users
fetch('http://localhost:3000/users')
.then((response)=>response.json()) //response.text()返回文本
.then((responseJson)=>{
Alert.alert(JSON.stringify(responseJson)) //json输出弹窗
console.warn(new Date().getMilliseconds());
})
.catch((error)=>{
console.warn(error)
}).done()
console.warn('证明请求是异步的:'+ new Date().getMilliseconds());

XMLHttpRequest方式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
var request = new XMLHttpRequest();
request.onreadystatechange = (e) => {
if (request.readyState !== 4) {
return;
}
if (request.status === 200) {
console.log('success', request.responseText);
Alert.alert(request.responseText)
} else {
console.warn('error');
}
};
request.open('GET', 'http://localhost:3000/users');
request.send();

WebSocket

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
var ws = new WebSocket('ws://localhost:8080');
ws.onopen = () => {
// connection opened
ws.send('something123'); // send a message
};
ws.onmessage = (e) => {
// a message was received
console.log(e.data);
Alert.alert(e.data)
};
ws.onerror = (e) => {
// an error occurred
console.log(e.message);
};
ws.onclose = (e) => {
// connection closed
console.log(e.code, e.reason);
};

综合例子

用ES6的写法.

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
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View,
Image,
ActivityIndicatorIOS,
TouchableOpacity,
TouchableHighlight,
Navigator,
Alert,
} from 'react-native'
//导出组件
export default class HttpTest extends React.Component{
//自定义请求参数
fetchDetail(){
//POST 增加一个user
fetch('http://localhost:3000/users',{
method:'POST',
headers:{
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body:JSON.stringify({
name:'xuneng',
age:'123'
})
})
}
//fetch并处理返回(Promise,异步).
fetchCallback(){
//GET 获取所有users
fetch('http://localhost:3000/users')
.then((response)=>response.json()) //response.text()返回文本
.then((responseJson)=>{
Alert.alert(JSON.stringify(responseJson)) //json输出弹窗
console.warn(new Date().getMilliseconds());
})
.catch((error)=>{
console.warn(error)
}).done()
console.warn('证明请求是异步的:'+ new Date().getMilliseconds());
}
//使用XMLHttpRequest或其他3方库处理网络请求
myXMLHttpRequest(){
var request = new XMLHttpRequest();
request.onreadystatechange = (e) => {
if (request.readyState !== 4) {
return;
}
if (request.status === 200) {
console.log('success', request.responseText);
Alert.alert(request.responseText)
} else {
console.warn('error');
}
};
request.open('GET', 'http://localhost:3000/users');
request.send();
}
//WebSocket
myWebSocket(){
var ws = new WebSocket('ws://localhost:8080');
ws.onopen = () => {
// connection opened
ws.send('something123'); // send a message
};
ws.onmessage = (e) => {
// a message was received
console.log(e.data);
Alert.alert(e.data)
};
ws.onerror = (e) => {
// an error occurred
console.log(e.message);
};
ws.onclose = (e) => {
// connection closed
console.log(e.code, e.reason);
};
}
render(){
return (
<View style={{flex:1,justifyContent:'center',alignItems:'center'}}>
<TouchableOpacity style={mystyle.button} onPress={this.fetchDetail.bind(this)}>
<Text>Fetch detail</Text>
</TouchableOpacity>
<TouchableOpacity style={mystyle.button} onPress={this.fetchCallback.bind(this)}>
<Text>Fetch With Callback</Text>
</TouchableOpacity>
<TouchableOpacity style={mystyle.button} onPress={this.myXMLHttpRequest.bind(this)}>
<Text>XMLHttpRequest处理请求</Text>
</TouchableOpacity>
<TouchableOpacity style={mystyle.button} onPress={this.myWebSocket.bind(this)}>
<Text>WebSocket</Text>
</TouchableOpacity>
</View>
)
}
}
var mystyle = StyleSheet.create({
button:{
width:180,
height:50,
justifyContent:'center',
backgroundColor:'#e2e',
alignItems:'center',
margin:15
}
})

参考: https://facebook.github.io/react-native/docs/network.html#content

转载请注明出处,有疑问欢迎留言!