前言
modlue怎么能少得了网络请求尼(-_-),本篇博文介绍下Weex Moudle中的stream使用与源码分析~
代码分析
sendHttp(params, callback) : 网络请求
weex code
Arguments
params(object): 请求参数.
method(string): 方法例如: GET, POST.
url(string): 请求url.
header(object): 请求头.
body(string): 请求body.
callback(function): A callback function whose argument is the response string of the request. Example var stream = require(‘@weex-module/stream’);
stream.sendHttp({ method: ‘GET’, url: ‘path/to/a/uri’, }, function(ret) { // TODO 成功回调 });
封装api utils
/** * Created by walid on 16/6/13. * params : {method:POST/GET,url:http://xxx,header:{key:value}, * body:{key:value}} */
var stream = require(‘@weex-module/stream’);
// 定义所需常量
var apiURL = {
baseXbUrl: ‘http://www.***.***’,
getData: ‘/v1/xxx/api1’
};
function requestGet(url, callback) {
stream.sendHttp({
method: ‘GET’,
url: apiURL.baseXbUrl + url
}, function(ret) {
var retdata = JSON.parse(ret);
callback(retdata);
});
}
function requestPost(url, callback) {
requestPostWithBody(url, null, callback);
}
function requestPostWithBody(url, body, callback) {
stream.sendHttp({
method: ‘POST’,
url: apiURL.baseXbUrl + url,
body: body
}, function(ret) {
var retdata = JSON.parse(ret);
callback(retdata);
});
}
// 导出 获取数据方法
exports.getData= function(callback) {
requestPostWithBody(apiURL.getData, {
“start”: start
}, callback);
};
android code
WXSDKEngine.registerModule(“stream”, WXStreamModule.class);
1、WXStreamModule
@WXModuleAnno
public void sendHttp(String params, String callback) {
// 获取请求数据
JSONObject paramsObj = JSON.parseObject(params);
String method = paramsObj.getString(“method”);
String url = paramsObj.getString(“url”);
JSONObject header = paramsObj.getJSONObject(“header”);
final String body = paramsObj.getString(“body”);
// 拼接请求
WXRequest wxRequest = new WXRequest();
wxRequest.method = method;
wxRequest.url = url;
wxRequest.body = body;
// 保存header到map
if (wxRequest.paramMap == null) {
wxRequest.paramMap = new HashMap();
}
if (header != null) {
for (String key : header.keySet()) {
wxRequest.paramMap.put(key, header.get(key));
}
}
// 调用httpadapter进行数据获取
if (mWXSDKInstance != null && mWXSDKInstance.getWXHttpAdapter() != null) {
mWXSDKInstance.getWXHttpAdapter().sendRequest(wxRequest,
new StreamHttpListener(mWXSDKInstance.getInstanceId(), callback));
}
}
private class StreamHttpListener implements IWXHttpAdapter.OnHttpListener {
private String mInstanceId;
private String mCallback;
private StreamHttpListener(String instanceId, String callbak) {
mInstanceId = instanceId;
mCallback = callbak;
}
@Override
public void onHttpStart() {}
@Override
public void onHttpUploadProgress(int uploadProgress) {}
@Override
public void onHttpResponseProgress(int responseProgress) {}
// 接受response数据
@Override
public void onHttpFinish(final WXResponse response) {
WXSDKManager.getInstance().postOnUiThread(new Runnable() {
@Override
public void run() {
WXBridgeManager.getInstance().callback(mInstanceId, mCallback,
(response == null || response.originalData == null) ? “{}” :
new String(response.originalData));
}
}, 0);
if (WXEnvironment.isApkDebugable()) {
response.originalData != null ? new String(response.originalData) :
“response data is NUll!”);
}
}
}
2、自定义httpadapter
/** * Author: walid * Date : 2016/6/13 16:00 */
public class XbHttpAdapter implements IWXHttpAdapter {
@Override
public void sendRequest(final WXRequest request, final OnHttpListener listener) {
if (listener != null) {
listener.onHttpStart();
}
Date data = new Date();
// 添加 header
request.paramMap.put(“device-id”, AuthUtil.getDeviceId());
request.paramMap.put(“app-time”, String.valueOf(data.getTime()));
request.paramMap.put(“app-minorid”, AuthUtil.getAppMinorId());
request.paramMap.put(“app-id”, AuthUtil.getAppId());
request.paramMap.put(“user-agent”, AuthUtil.getUserAgent());
// 发起请求
WXHttpManager.getInstance().execute(new Runnable() {
@Override
public void run() {
WXResponse response = new WXResponse();
try {
HttpURLConnection connection = openConnection(request, listener);
int responseCode = connection.getResponseCode();
response.statusCode = String.valueOf(responseCode);
if (responseCode == 200 || responseCode == 202) {
response.originalData =
readInputStream(connection.getInputStream(), listener).getBytes();
} else {
response.errorMsg = readInputStream(connection.getErrorStream(), listener);
}
if (listener != null) {
listener.onHttpFinish(response);
}
} catch (IOException e) {
e.printStackTrace();
response.errorCode = “-1”;
response.errorMsg = e.getMessage();
if (listener != null) {
listener.onHttpFinish(response);
}
}
}
});
}
private HttpURLConnection openConnection(WXRequest request, OnHttpListener listener)
throws IOException {
URL url = new URL(request.url);
HttpURLConnection connection = createConnection(url);
connection.setConnectTimeout(request.timeoutMs);
connection.setReadTimeout(request.timeoutMs);
connection.setUseCaches(false);
connection.setDoInput(true);
/* header */
if (request.paramMap != null) {
Set keySets = request.paramMap.keySet();
for (String key : keySets) {
connection.addRequestProperty(key, request.paramMap.get(key).toString());
}
}
/* method */
String method = request.method;
if (!TextUtils.isEmpty(method)) {
connection.setRequestMethod(method);
/* body */
if (method.equals(“POST”)) {
if (listener != null) {
listener.onHttpUploadProgress(0);
}
DataOutputStream out = new DataOutputStream(connection.getOutputStream());
out.write(request.body.getBytes());
out.close();
if (listener != null) {
listener.onHttpUploadProgress(100);
}
}
}
return connection;
}
// 读取数据
private String readInputStream(InputStream inputStream, OnHttpListener listener) {
StringBuilder builder = new StringBuilder();
try {
int fileLen = inputStream.available();
BufferedReader localBufferedReader =
new BufferedReader(new InputStreamReader(inputStream));
char[] data = new char[2048];
int len;
while ((len = localBufferedReader.read(data)) > 0) {
builder.append(data, 0, len);
if (listener != null && fileLen > 0) {
listener.onHttpResponseProgress((builder.length() / fileLen) * 100);
}
}
localBufferedReader.close();
try {
inputStream.close();
} catch (IOException e) {
WXLogUtils.e(“DefaultWXHttpAdapter: ” + WXLogUtils.getStackTrace(e));
}
} catch (IOException e) {
e.printStackTrace();
}
String result = String.valueOf(builder);
try {
JSONObject jsonObject = JSON.parseObject(result);
String data = jsonObject.getString(“data”);
Logger.d(“result = ” + jsonObject);
return String.valueOf(jsonObject);
} catch (Exception e) {
Logger.d(“result = ” + result);
return result;
}
}
protected HttpURLConnection createConnection(URL url) throws IOException {
return (HttpURLConnection) url.openConnection();
}
}
1、拦截到js代码中发送请求操作,组装数据;
2、调用httpadapter进行网络连接;
3、连接成功回调js callback返回数据;
4、刷新UI;