Search in sources :

Example 16 with WXRequest

use of com.taobao.weex.common.WXRequest 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 17 with WXRequest

use of com.taobao.weex.common.WXRequest 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 18 with WXRequest

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

the class TypeFaceHandler method requestRemoteIcon.

private static void requestRemoteIcon(final WXRequest request, final IWXHttpAdapter.OnHttpListener listener) {
    final WXResponse wxResponse = new WXResponse();
    String method = request.method;
    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()));
        }
    }
    DefaultWXHttpAdapter adapter = (DefaultWXHttpAdapter) WXSDKManager.getInstance().getIWXHttpAdapter();
    OkHttpClient httpClient = adapter.getHttpClient();
    httpClient.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 {
                // success
                if (listener != null) {
                    listener.onHttpFinish(wxResponse);
                }
            }
        }
    });
}
Also used : Call(okhttp3.Call) OkHttpClient(okhttp3.OkHttpClient) HashMap(java.util.HashMap) WXRequest(com.taobao.weex.common.WXRequest) Request(okhttp3.Request) IOException(java.io.IOException) WXResponse(com.taobao.weex.common.WXResponse) DefaultWXHttpAdapter(com.eros.framework.extend.adapter.DefaultWXHttpAdapter) Response(okhttp3.Response) WXResponse(com.taobao.weex.common.WXResponse) Callback(okhttp3.Callback) HashMap(java.util.HashMap) Map(java.util.Map) RequestBody(okhttp3.RequestBody)

Example 19 with WXRequest

use of com.taobao.weex.common.WXRequest 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 20 with WXRequest

use of com.taobao.weex.common.WXRequest 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

WXRequest (com.taobao.weex.common.WXRequest)23 IWXHttpAdapter (com.taobao.weex.adapter.IWXHttpAdapter)17 WXResponse (com.taobao.weex.common.WXResponse)9 WXSDKInstanceTest (com.taobao.weex.WXSDKInstanceTest)8 JSCallback (com.taobao.weex.bridge.JSCallback)8 Test (org.junit.Test)8 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)8 Uri (android.net.Uri)4 IOException (java.io.IOException)3 HashMap (java.util.HashMap)3 List (java.util.List)3 Map (java.util.Map)3 Call (okhttp3.Call)3 Request (okhttp3.Request)3 RequestBody (okhttp3.RequestBody)3 Response (okhttp3.Response)3 Paint (android.graphics.Paint)2 JSONObject (com.alibaba.fastjson.JSONObject)2 WXSDKManager (com.taobao.weex.WXSDKManager)2 WXDomObject (com.taobao.weex.dom.WXDomObject)2