Search in sources :

Example 1 with WXResponse

use of com.taobao.weex.common.WXResponse in project weex-example by KalicyZhou.

the class WXStreamModuleTest method testFetchStatus.

@Test
public void testFetchStatus() throws Exception {
    WXStreamModule streamModule = createModule(new IWXHttpAdapter() {

        @Override
        public void sendRequest(WXRequest request, OnHttpListener listener) {
            WXResponse response = new WXResponse();
            response.statusCode = "-1";
            listener.onHttpFinish(response);
        }
    });
    Callback finish = new Callback();
    streamModule.fetch("", finish, null);
    assertEquals(finish.mData.get(WXStreamModule.STATUS_TEXT), Status.ERR_INVALID_REQUEST);
    streamModule.fetch("{method: 'POST',url: 'http://httpbin.org/post',type:'json'}", finish, null);
    assertEquals(finish.mData.get(WXStreamModule.STATUS_TEXT), Status.ERR_CONNECT_FAILED);
    streamModule = createModule(new IWXHttpAdapter() {

        @Override
        public void sendRequest(WXRequest request, OnHttpListener listener) {
            WXResponse response = new WXResponse();
            response.statusCode = "302";
            listener.onHttpFinish(response);
        }
    });
    streamModule.fetch("{method: 'POST',url: 'http://httpbin.org/post',type:'json'}", finish, null);
    assertEquals(finish.mData.get(WXStreamModule.STATUS), 302);
    assertEquals(finish.mData.get(WXStreamModule.STATUS).getClass(), Integer.class);
    assertEquals(finish.mData.get(WXStreamModule.STATUS_TEXT), Status.getStatusText("302"));
}
Also used : JSCallback(com.taobao.weex.bridge.JSCallback) IWXHttpAdapter(com.taobao.weex.adapter.IWXHttpAdapter) WXRequest(com.taobao.weex.common.WXRequest) WXResponse(com.taobao.weex.common.WXResponse) Test(org.junit.Test) WXSDKInstanceTest(com.taobao.weex.WXSDKInstanceTest) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Example 2 with WXResponse

use of com.taobao.weex.common.WXResponse in project weex-example by KalicyZhou.

the class WXStreamModule method fetch.

/**
   *
   * @param optionsStr request options include:
   *  method: GET 、POST、PUT、DELETE、HEAD、PATCH
   *  headers:object,请求header
   *  url:
   *  body: "Any body that you want to add to your request"
   *  type: json、text、jsonp(native实现时等价与json)
   * @param callback finished callback,response object:
   *  status:status code
   *  ok:boolean 是否成功,等价于status200~299
   *  statusText:状态消息,用于定位具体错误原因
   *  data: 响应数据,当请求option中type为json,时data为object,否则data为string类型
   *  headers: object 响应头
   *
   * @param progressCallback in progress callback,for download progress and request state,response object:
   *  readyState: number 请求状态,1 OPENED,开始连接;2 HEADERS_RECEIVED;3 LOADING
   *  status:status code
   *  length:当前获取的字节数,总长度从headers里「Content-Length」获取
   *  statusText:状态消息,用于定位具体错误原因
   *  headers: object 响应头
   */
@JSMethod(uiThread = false)
public void fetch(String optionsStr, final JSCallback callback, JSCallback progressCallback) {
    JSONObject optionsObj = null;
    try {
        optionsObj = JSON.parseObject(optionsStr);
    } catch (JSONException e) {
        WXLogUtils.e("", e);
    }
    boolean invaildOption = optionsObj == null || optionsObj.getString("url") == null;
    if (invaildOption) {
        if (callback != null) {
            Map<String, Object> resp = new HashMap<>();
            resp.put("ok", false);
            resp.put(STATUS_TEXT, Status.ERR_INVALID_REQUEST);
            callback.invoke(resp);
        }
        return;
    }
    String method = optionsObj.getString("method");
    String url = optionsObj.getString("url");
    JSONObject headers = optionsObj.getJSONObject("headers");
    String body = optionsObj.getString("body");
    String type = optionsObj.getString("type");
    int timeout = optionsObj.getIntValue("timeout");
    if (method != null)
        method = method.toUpperCase();
    Options.Builder builder = new Options.Builder().setMethod(!"GET".equals(method) && !"POST".equals(method) && !"PUT".equals(method) && !"DELETE".equals(method) && !"HEAD".equals(method) && !"PATCH".equals(method) ? "GET" : method).setUrl(url).setBody(body).setType(type).setTimeout(timeout);
    extractHeaders(headers, builder);
    final Options options = builder.createOptions();
    sendRequest(options, new ResponseCallback() {

        @Override
        public void onResponse(WXResponse response, Map<String, String> headers) {
            if (callback != null) {
                Map<String, Object> resp = new HashMap<>();
                if (response == null || "-1".equals(response.statusCode)) {
                    resp.put(STATUS, -1);
                    resp.put(STATUS_TEXT, Status.ERR_CONNECT_FAILED);
                } else {
                    int code = Integer.parseInt(response.statusCode);
                    resp.put(STATUS, code);
                    resp.put("ok", (code >= 200 && code <= 299));
                    if (response.originalData == null) {
                        resp.put("data", null);
                    } else {
                        String respData = readAsString(response.originalData, headers != null ? getHeader(headers, "Content-Type") : "");
                        try {
                            resp.put("data", parseData(respData, options.getType()));
                        } catch (JSONException exception) {
                            WXLogUtils.e("", exception);
                            resp.put("ok", false);
                            resp.put("data", "{'err':'Data parse failed!'}");
                        }
                    }
                    resp.put(STATUS_TEXT, Status.getStatusText(response.statusCode));
                }
                resp.put("headers", headers);
                callback.invoke(resp);
            }
        }
    }, progressCallback);
}
Also used : HashMap(java.util.HashMap) JSONException(com.alibaba.fastjson.JSONException) WXResponse(com.taobao.weex.common.WXResponse) JSONObject(com.alibaba.fastjson.JSONObject) JSONObject(com.alibaba.fastjson.JSONObject) HashMap(java.util.HashMap) Map(java.util.Map) JSMethod(com.taobao.weex.annotation.JSMethod)

Example 3 with WXResponse

use of com.taobao.weex.common.WXResponse in project weex-example by KalicyZhou.

the class WXStreamModule method sendHttp.

/**
   * send HTTP request
   *
   * @param params   {method:POST/GET/PUT/DELETE/HEAD/PATCH,url:http://xxx,header:{key:value},
   *                 body:{key:value}}
   * @param callback formate:handler(err, response)
   */
@Deprecated
@JSMethod(uiThread = false)
public void sendHttp(String params, final String callback) {
    JSONObject paramsObj = JSON.parseObject(params);
    String method = paramsObj.getString("method");
    String url = paramsObj.getString("url");
    JSONObject headers = paramsObj.getJSONObject("header");
    String body = paramsObj.getString("body");
    int timeout = paramsObj.getIntValue("timeout");
    if (method != null)
        method = method.toUpperCase();
    Options.Builder builder = new Options.Builder().setMethod(!"GET".equals(method) && !"POST".equals(method) && !"PUT".equals(method) && !"DELETE".equals(method) && !"HEAD".equals(method) && !"PATCH".equals(method) ? "GET" : method).setUrl(url).setBody(body).setTimeout(timeout);
    extractHeaders(headers, builder);
    sendRequest(builder.createOptions(), new ResponseCallback() {

        @Override
        public void onResponse(WXResponse response, Map<String, String> headers) {
            if (callback != null && mWXSDKInstance != null)
                WXBridgeManager.getInstance().callback(mWXSDKInstance.getInstanceId(), callback, (response == null || response.originalData == null) ? "{}" : readAsString(response.originalData, headers != null ? getHeader(headers, "Content-Type") : ""));
        }
    }, null);
}
Also used : JSONObject(com.alibaba.fastjson.JSONObject) WXResponse(com.taobao.weex.common.WXResponse) JSMethod(com.taobao.weex.annotation.JSMethod)

Example 4 with WXResponse

use of com.taobao.weex.common.WXResponse in project weex-example by KalicyZhou.

the class DefaultWXHttpAdapter method sendRequest.

@Override
public void sendRequest(final WXRequest request, final OnHttpListener listener) {
    if (listener != null) {
        listener.onHttpStart();
    }
    execute(new Runnable() {

        @Override
        public void run() {
            WXResponse response = new WXResponse();
            IEventReporterDelegate reporter = getEventReporterDelegate();
            try {
                HttpURLConnection connection = openConnection(request, listener);
                reporter.preConnect(connection, request.body);
                Map<String, List<String>> headers = connection.getHeaderFields();
                int responseCode = connection.getResponseCode();
                if (listener != null) {
                    listener.onHeadersReceived(responseCode, headers);
                }
                reporter.postConnect();
                response.statusCode = String.valueOf(responseCode);
                if (responseCode >= 200 && responseCode <= 299) {
                    InputStream rawStream = connection.getInputStream();
                    rawStream = reporter.interpretResponseStream(rawStream);
                    response.originalData = readInputStreamAsBytes(rawStream, listener);
                } else {
                    response.errorMsg = readInputStream(connection.getErrorStream(), listener);
                }
                if (listener != null) {
                    listener.onHttpFinish(response);
                }
            } catch (IOException | IllegalArgumentException e) {
                e.printStackTrace();
                response.statusCode = "-1";
                response.errorCode = "-1";
                response.errorMsg = e.getMessage();
                if (listener != null) {
                    listener.onHttpFinish(response);
                }
                if (e instanceof IOException) {
                    reporter.httpExchangeFailed((IOException) e);
                }
            }
        }
    });
}
Also used : HttpURLConnection(java.net.HttpURLConnection) InputStream(java.io.InputStream) IOException(java.io.IOException) Map(java.util.Map) WXResponse(com.taobao.weex.common.WXResponse)

Example 5 with WXResponse

use of com.taobao.weex.common.WXResponse in project WeexErosFramework by bmfe.

the class DefaultWXHttpAdapter method doInterceptor.

private void doInterceptor(WXRequest request, OnHttpListener listener) {
    WXResponse response = new WXResponse();
    String url = request.url;
    if (TextUtils.isEmpty(url)) {
        if (listener != null) {
            response.statusCode = "-1";
            response.errorCode = "-1";
            response.errorMsg = "路径不能为空";
            listener.onHttpFinish(response);
        }
        return;
    }
    String subPath = url.substring(url.indexOf("/dist/js") + 9);
    File bundleDir = ManagerFactory.getManagerService(FileManager.class).getBundleDir(mContext);
    File path = new File(bundleDir, "bundle/" + subPath);
    Log.e("bus", "bus>>>>>>>" + path.getAbsolutePath());
    if (listener != null) {
        listener.onHttpStart();
    }
    if (path.exists()) {
        // 比较md5
        String targetMd5 = findMd5(path.getAbsolutePath());
        String currentMd5 = Md5Util.getFileMD5(path);
        if (currentMd5 == null) {
            // 纪录错误   md5映射中找不到该路径
            if (listener != null) {
                response.statusCode = "-1";
                response.errorCode = "-1";
                response.errorMsg = "映射中找不到:" + path.getAbsolutePath();
                listener.onHttpFinish(response);
            }
            showError("不存在md5映射");
            return;
        }
        if (!targetMd5.equals(currentMd5)) {
            // 纪录错误  得到的md5与映射中md5不一致
            if (listener != null) {
                response.statusCode = "-1";
                response.errorCode = "-1";
                response.errorMsg = "文件不匹配" + path.getAbsolutePath();
                listener.onHttpFinish(response);
            }
            showError("当前md5和config中的md5不一致");
            return;
        }
        // 文件正确  加载本地js
        byte[] bytes = ManagerFactory.getManagerService(FileManager.class).loadLocalFile(path.getAbsolutePath());
        if (listener != null) {
            response.statusCode = 200 + "";
            if (isInterceptor(request.url)) {
                // response.originalData = appendBaseJs(bytes);
                response.originalData = bytes;
                appendBaseJs(response, listener);
            } else {
                // iconFont
                response.originalData = bytes;
                listener.onHttpFinish(response);
            }
        }
        hideError();
    } else {
        if (listener != null) {
            response.statusCode = "-1";
            response.errorCode = "-1";
            response.errorMsg = "文件不存在" + path.getAbsolutePath();
            listener.onHttpFinish(response);
        }
        showError("文件" + path.getAbsolutePath() + "不存在");
    }
}
Also used : File(java.io.File) FileManager(com.benmu.framework.manager.impl.FileManager) WXResponse(com.taobao.weex.common.WXResponse)

Aggregations

WXResponse (com.taobao.weex.common.WXResponse)16 WXRequest (com.taobao.weex.common.WXRequest)6 IWXHttpAdapter (com.taobao.weex.adapter.IWXHttpAdapter)5 Map (java.util.Map)5 JSONObject (com.alibaba.fastjson.JSONObject)4 JSMethod (com.taobao.weex.annotation.JSMethod)4 IOException (java.io.IOException)3 HashMap (java.util.HashMap)3 List (java.util.List)3 Paint (android.graphics.Paint)2 JSONException (com.alibaba.fastjson.JSONException)2 WXSDKInstanceTest (com.taobao.weex.WXSDKInstanceTest)2 JSCallback (com.taobao.weex.bridge.JSCallback)2 InputStream (java.io.InputStream)2 HttpURLConnection (java.net.HttpURLConnection)2 Call (okhttp3.Call)2 Response (okhttp3.Response)2 Test (org.junit.Test)2 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)2 AlertDialog (android.app.AlertDialog)1