最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Android webview not loading css and javascript when trying to access webpage using custom headers - Stack Overflow

programmeradmin3浏览0评论

I am using authorization headers to access the web page, but when using WebViewClient with authorization headers the webview not rendering the css and also the js not loading.

    public class TableViewTest extends AppCompatActivity {

    WebView webView;
    SharedPreferences pref;

    @SuppressLint("SetJavaScriptEnabled")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_table_view_test);

        String url = "http://myurl";
        pref = getSharedPreferences("app", Context.MODE_PRIVATE);


        webView = (WebView) findViewById(R.id.webView1Id);

        webView.setWebViewClient(wvc);
        //webView.setVerticalScrollBarEnabled(true);
        //webView.setHorizontalScrollBarEnabled(true);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.getSettings().setBuiltInZoomControls(true);
        webView.getSettings().setDomStorageEnabled(true);
        webView.getSettings().setUseWideViewPort(true);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            webView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_COMPATIBILITY_MODE);
            webView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        //webView.setLayerType(View.LAYER_TYPE_HARDWARE, null);

        webView.loadUrl("http://myurl");

    }


    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        webView.saveState(outState);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        webView.restoreState(savedInstanceState);
    }


    WebViewClient wvc = new WebViewClient() {

        @SuppressWarnings("deprecation")
        public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
            try {
                final String acToken = pref.getString("token", "DEFAULT");

                OkHttpClient okHttpClient = new OkHttpClient();
                Request request = new Request.Builder().url(url).addHeader("Authorization", "Bearer " + acToken)
                        .build();

                Response response = okHttpClient.newCall(request).execute();

                return new WebResourceResponse(response.header("text/html", response.body().contentType().type()), // You can set something other as default content-type
                        response.header("content-encoding", "utf-8"),  // Again, you can set another encoding as default
                        response.body().byteStream());


            } catch (ClientProtocolException e) {
                //return null to tell WebView we failed to fetch it WebView should try again.
                return null;
            } catch (IOException e) {
                e.printStackTrace();
                return null;
            }
        }
    };
}

Please help me. Any help is appreciated.

I am using authorization headers to access the web page, but when using WebViewClient with authorization headers the webview not rendering the css and also the js not loading.

    public class TableViewTest extends AppCompatActivity {

    WebView webView;
    SharedPreferences pref;

    @SuppressLint("SetJavaScriptEnabled")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_table_view_test);

        String url = "http://myurl";
        pref = getSharedPreferences("app", Context.MODE_PRIVATE);


        webView = (WebView) findViewById(R.id.webView1Id);

        webView.setWebViewClient(wvc);
        //webView.setVerticalScrollBarEnabled(true);
        //webView.setHorizontalScrollBarEnabled(true);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.getSettings().setBuiltInZoomControls(true);
        webView.getSettings().setDomStorageEnabled(true);
        webView.getSettings().setUseWideViewPort(true);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            webView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_COMPATIBILITY_MODE);
            webView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        //webView.setLayerType(View.LAYER_TYPE_HARDWARE, null);

        webView.loadUrl("http://myurl");

    }


    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        webView.saveState(outState);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        webView.restoreState(savedInstanceState);
    }


    WebViewClient wvc = new WebViewClient() {

        @SuppressWarnings("deprecation")
        public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
            try {
                final String acToken = pref.getString("token", "DEFAULT");

                OkHttpClient okHttpClient = new OkHttpClient();
                Request request = new Request.Builder().url(url).addHeader("Authorization", "Bearer " + acToken)
                        .build();

                Response response = okHttpClient.newCall(request).execute();

                return new WebResourceResponse(response.header("text/html", response.body().contentType().type()), // You can set something other as default content-type
                        response.header("content-encoding", "utf-8"),  // Again, you can set another encoding as default
                        response.body().byteStream());


            } catch (ClientProtocolException e) {
                //return null to tell WebView we failed to fetch it WebView should try again.
                return null;
            } catch (IOException e) {
                e.printStackTrace();
                return null;
            }
        }
    };
}

Please help me. Any help is appreciated.

Share Improve this question asked Jan 8, 2017 at 6:14 Sudheesh RSudheesh R 1,7753 gold badges25 silver badges44 bronze badges 3
  • Im facing the same problem. Have you find a solution? – Federico Picci Commented Feb 9, 2017 at 14:27
  • @Picci My web service API developer solved the issue by creating style class for each one of the table element. Because the CSS referral via child classes are not loading in the web view. And after that, we changed to link. This is an awesome library. But we can not use the headers across all links in the web view. Its restricted to the initial request. Thanks for your effort to mention this. #HappyToHelp #HappyCoding – Sudheesh R Commented Feb 12, 2017 at 5:42
  • @Picci Actually my web view was loading a table format – Sudheesh R Commented Feb 12, 2017 at 5:50
Add a ment  | 

2 Answers 2

Reset to default 2

Used AdvancedWebView library to overe the issues. The default webview in android can not handle the css issues sometimes.

And also both Android webview and AdvancedWebView Can not handle the headers except in initial request in the webview. It can not pass the headers across all the links in particular webview request. Please refer this to rectify your doubts Github Question.

My SO Question for the headers issue.

If anybody finds the solution for the above header passing issue, feel free to add your solution. Thank you.

This works for me.

(btw is deprecated now)

WebViewClient wvc = new WebViewClient() {

                @Override
                public WebResourceResponse shouldInterceptRequest (WebView view, String url){
                    try {
                        OkHttpClient httpClient = new OkHttpClient();
                        .squareup.okhttp.Request request = new .squareup.okhttp.Request.Builder()
                                .url(url.trim())
                                .addHeader("PIPPO", "PIPPO")
                                .build();
                        .squareup.okhttp.Response response = httpClient.newCall(request).execute();

                        Log.d("TAG",response.header("content-type", "text/html"));
                        Log.d("TAG",response.header("content-encoding",  "UTF-8"));

                        return new WebResourceResponse(
                                null,
                                null,
                                response.body().byteStream()
                        );
                        } catch (Exception e) {
                        //return null to tell WebView we failed to fetch it WebView should try again.
                        return null;
                    }
            }

My only fear is that on smartphones with "problematic" default browser, the result may be broken.

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论