Search in sources :

Example 11 with WXResponse

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

the class WXStreamModuleTest method successResponse.

private WXResponse successResponse() {
    WXResponse resp = new WXResponse();
    resp.data = "data";
    resp.statusCode = "200";
    return resp;
}
Also used : WXResponse(com.taobao.weex.common.WXResponse)

Example 12 with WXResponse

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

the class TypefaceUtil method downloadFontByNetwork.

private static void downloadFontByNetwork(final String url, final String fullPath, final String fontFamily) {
    IWXHttpAdapter adapter = WXSDKManager.getInstance().getIWXHttpAdapter();
    if (adapter == null) {
        WXLogUtils.e(TAG, "downloadFontByNetwork() IWXHttpAdapter == null");
        return;
    }
    WXRequest request = new WXRequest();
    request.url = url;
    request.method = "GET";
    adapter.sendRequest(request, new IWXHttpAdapter.OnHttpListener() {

        @Override
        public void onHttpStart() {
            if (WXEnvironment.isApkDebugable()) {
                WXLogUtils.d(TAG, "downloadFontByNetwork begin url:" + url);
            }
        }

        @Override
        public void onHeadersReceived(int statusCode, Map<String, List<String>> headers) {
        }

        @Override
        public void onHttpUploadProgress(int uploadProgress) {
        }

        @Override
        public void onHttpResponseProgress(int loadedLength) {
        }

        @Override
        public void onHttpFinish(WXResponse response) {
            int statusCode = 0;
            if (!TextUtils.isEmpty(response.statusCode)) {
                try {
                    statusCode = Integer.parseInt(response.statusCode);
                } catch (NumberFormatException e) {
                    statusCode = 0;
                    WXLogUtils.e(TAG, "IWXHttpAdapter onHttpFinish statusCode:" + response.statusCode);
                }
            }
            boolean result;
            if (statusCode >= 200 && statusCode <= 299 && response.originalData != null) {
                result = WXFileUtils.saveFile(fullPath, response.originalData, WXEnvironment.getApplication());
                if (result) {
                    result = loadLocalFontFile(fullPath, fontFamily);
                } else {
                    if (WXEnvironment.isApkDebugable()) {
                        WXLogUtils.d(TAG, "downloadFontByNetwork() onHttpFinish success, but save file failed.");
                    }
                }
            } else {
                result = false;
            }
            if (!result) {
                FontDO fontDO = sCacheMap.get(fontFamily);
                if (fontDO != null) {
                    fontDO.setState(FontDO.STATE_FAILED);
                }
            }
        }
    });
}
Also used : IWXHttpAdapter(com.taobao.weex.adapter.IWXHttpAdapter) List(java.util.List) WXRequest(com.taobao.weex.common.WXRequest) Paint(android.graphics.Paint) WXResponse(com.taobao.weex.common.WXResponse)

Example 13 with WXResponse

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

the class DefaultWXHttpAdapter method fetchUrl.

private void fetchUrl(final WXRequest request, final OnHttpListener listener) {
    final WXResponse wxResponse = new WXResponse();
    String method = request.method == null ? "GET" : request.method.toUpperCase();
    String requestBodyString = request.body == null ? "{}" : request.body;
    RequestBody body = null;
    if (request.paramMap != null && request.paramMap.containsKey("Content-Type")) {
        body = HttpMethod.requiresRequestBody(method) ? RequestBody.create(MediaType.parse(request.paramMap.get("Content-Type")), requestBodyString) : null;
    } else {
        body = HttpMethod.requiresRequestBody(method) ? RequestBody.create(MediaType.parse("application/x-www-form-urlencoded;charset=UTF-8"), requestBodyString) : null;
    }
    Request.Builder requestBuilder = new Request.Builder().url(request.url).method(method, body);
    if (request.paramMap != null) {
        for (Map.Entry<String, String> param : request.paramMap.entrySet()) {
            requestBuilder.addHeader(param.getKey(), TextUtil.toHumanReadableAscii(param.getValue()));
        }
    }
    client.newCall(requestBuilder.build()).enqueue(new Callback() {

        @Override
        public void onFailure(Call call, IOException e) {
            wxResponse.errorMsg = e.getMessage();
            wxResponse.errorCode = "-1";
            wxResponse.statusCode = "-1";
            if (listener != null) {
                listener.onHttpFinish(wxResponse);
            }
        }

        @Override
        public void onResponse(Call call, Response response) {
            byte[] responseBody = new byte[0];
            try {
                responseBody = response.body().bytes();
            } catch (IOException e) {
                e.printStackTrace();
                wxResponse.errorMsg = e.getMessage();
                wxResponse.errorCode = "-1";
                wxResponse.statusCode = "-1";
                if (listener != null) {
                    listener.onHttpFinish(wxResponse);
                }
            }
            wxResponse.data = new String(responseBody);
            wxResponse.statusCode = String.valueOf(response.code());
            wxResponse.originalData = responseBody;
            wxResponse.extendParams = new HashMap<>();
            for (Map.Entry<String, List<String>> entry : response.headers().toMultimap().entrySet()) {
                wxResponse.extendParams.put(entry.getKey(), entry.getValue());
            }
            if (response.code() < 200 || response.code() > 299) {
                wxResponse.errorMsg = response.message();
                if (listener != null) {
                    listener.onHttpFinish(wxResponse);
                }
            } else {
                if (isInterceptor(request.url)) {
                    appendBaseJs(wxResponse, listener);
                    // listener);
                    if (listener != null) {
                        listener.onHttpFinish(wxResponse);
                    }
                } else {
                    // iconFont
                    if (listener != null) {
                        listener.onHttpFinish(wxResponse);
                    }
                }
            }
        }
    });
}
Also used : Call(okhttp3.Call) HashMap(java.util.HashMap) Request(okhttp3.Request) WXRequest(com.taobao.weex.common.WXRequest) IOException(java.io.IOException) WXResponse(com.taobao.weex.common.WXResponse) WXResponse(com.taobao.weex.common.WXResponse) Response(okhttp3.Response) Callback(okhttp3.Callback) Map(java.util.Map) HashMap(java.util.HashMap) RequestBody(okhttp3.RequestBody)

Example 14 with WXResponse

use of com.taobao.weex.common.WXResponse in project incubator-weex by apache.

the class CheckForUpdateUtil method checkForUpdate.

public static void checkForUpdate(final Context context) {
    PackageManager pm = context.getPackageManager();
    try {
        PackageInfo info = pm.getPackageInfo(context.getPackageName(), 0);
        if (info != null) {
            int versionCode = info.versionCode;
            String updateUrl = "http://dotwe.org/release/latest?v=" + versionCode;
            WXRequest request = new WXRequest();
            request.method = "GET";
            request.url = updateUrl;
            WXLogUtils.d("Update", "check for update: " + versionCode);
            WXSDKManager.getInstance().getIWXHttpAdapter().sendRequest(request, new IWXHttpAdapter.OnHttpListener() {

                @Override
                public void onHttpStart() {
                }

                @Override
                public void onHeadersReceived(int statusCode, Map<String, List<String>> headers) {
                }

                @Override
                public void onHttpUploadProgress(int uploadProgress) {
                }

                @Override
                public void onHttpResponseProgress(int loadedLength) {
                }

                @Override
                public void onHttpFinish(final WXResponse response) {
                    if (!response.statusCode.equals("200")) {
                        WXLogUtils.e("Update", "failed: " + response.statusCode);
                        return;
                    }
                    WXSDKManager.getInstance().getWXRenderManager().postOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            String s = new String(response.originalData);
                            if (!TextUtils.isEmpty(s)) {
                                try {
                                    WXLogUtils.d("Update", s);
                                    JSONObject object = new JSONObject(s);
                                    JSONObject params = object.optJSONObject("params");
                                    if (params != null) {
                                        boolean hasUpdate = params.optBoolean("hasUpdate", false);
                                        if (hasUpdate) {
                                            String version = params.optString("version", "latest");
                                            String updateDate = params.optString("updateDate", "");
                                            final String updateUrl = params.optString("updateUrl", "");
                                            try {
                                                new URL(updateUrl);
                                            } catch (Throwable t) {
                                                WXLogUtils.e("Update", "Invalid update url");
                                                return;
                                            }
                                            String updateDescription = params.optString("updateDescription", null);
                                            AlertDialog.Builder builder = new AlertDialog.Builder(context);
                                            View view = LayoutInflater.from(context).inflate(R.layout.common_update_notify_dialog, null);
                                            TextView textView = (TextView) view.findViewById(R.id.common_update_dialog_msg);
                                            textView.setText(getMsg(version, updateDate, updateDescription));
                                            builder.setCancelable(false).setView(view).setPositiveButton(R.string.update_now, new DialogInterface.OnClickListener() {

                                                @Override
                                                public void onClick(DialogInterface dialog, int which) {
                                                    UpdateService.startActionUpdate(context, updateUrl);
                                                    dialog.dismiss();
                                                }
                                            });
                                            builder.setNegativeButton(R.string.update_remind_later, new DialogInterface.OnClickListener() {

                                                @Override
                                                public void onClick(DialogInterface dialog, int which) {
                                                    dialog.dismiss();
                                                }
                                            });
                                            builder.create().show();
                                        }
                                    }
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                    }, 0);
                }
            });
        }
    } catch (PackageManager.NameNotFoundException e) {
        e.printStackTrace();
    }
}
Also used : AlertDialog(android.app.AlertDialog) DialogInterface(android.content.DialogInterface) IWXHttpAdapter(com.taobao.weex.adapter.IWXHttpAdapter) URL(java.net.URL) WXResponse(com.taobao.weex.common.WXResponse) PackageManager(android.content.pm.PackageManager) List(java.util.List) TextView(android.widget.TextView) WXRequest(com.taobao.weex.common.WXRequest) PackageInfo(android.content.pm.PackageInfo) JSONException(org.json.JSONException) TextView(android.widget.TextView) View(android.view.View) JSONObject(org.json.JSONObject)

Example 15 with WXResponse

use of com.taobao.weex.common.WXResponse in project incubator-weex by apache.

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(JSON.parseObject("{}"), finish, null);
    assertEquals(finish.mData.get(WXStreamModule.STATUS_TEXT), Status.ERR_INVALID_REQUEST);
    streamModule.fetch(JSON.parseObject("{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(JSON.parseObject("{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) WXSDKInstanceTest(com.taobao.weex.WXSDKInstanceTest) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

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