欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

android webview 中 get 和 post 请求代码片段

程序员文章站 2022-05-02 23:46:53
一.get请求方法 loadUrlwebView.loadUrl(String url)二.post 请求方法 postUrlwebView.postUrl(String url, byte[] postData)# 例如StringBuilder builder = new StringBuilder();try {//拼接post提交参数 builder.append("token=").append(token);} catch (Exception e) {e.print...

一.get请求方法 loadUrl

webView.loadUrl(String url)

二.post 请求方法 postUrl
webView.postUrl(String url, byte[] postData)

# 例如
StringBuilder builder = new StringBuilder();
try {//拼接post提交参数
    builder.append("token=").append(token);
} catch (Exception e) {
	e.printStackTrace();
}
String postData = builder.toString();
webView.postUrl(url, EncodingUtils.getBytes(postData, "UTF-8"));

三.webview 初始化实例代码

 /***
     * 初始化webview
     */
    public void webView(String url) {
         
//        LayoutInflater inflater = LayoutInflater.from(this);
//        View popView = inflater.inflate(R.layout.bagview, null);
//        webView = (WebView) popView.findViewById(R.id.webView);
        //设置WebView的一些缩放功能点
        webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
        webView.setHorizontalScrollBarEnabled(false);
        webView.getSettings().setSupportZoom(true);
        //设置WebView触摸放大缩小
//        webView.getSettings().setBuiltInZoomControls(false);
//        webView.setInitialScale(70);
//        webView.setHorizontalScrollbarOverlay(true);
        //WebView双击变大,再双击后变小,当手动放大后,双击可以恢复到原始大小
        //webView.getSettings().setUseWideViewPort(true);
        //提高渲染的优先级
        webView.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
        //允许JS执行
        webView.getSettings().setJavaScriptEnabled(true);
        //把图片加载放在最后来加载渲染
        //webView.getSettings().setBlockNetworkImage(true);
        //用WebView将字符串以HTML的形式显示出来
        //webView.loadDataWithBaseURL("fake://not/needed", <p>zzz</p>, "text/html", "utf-8", "");
        //在同种分辨率的情况下,屏幕密度不一样的情况下,自动适配页面:
        DisplayMetrics dm = getResources().getDisplayMetrics();
        // 获取当前界面的高度
        //int width = dm.widthPixels;
        //int height = dm.heightPixels;
        int scale = dm.densityDpi;
        if (scale >= 240) {
            webView.getSettings().setDefaultZoom(WebSettings.ZoomDensity.FAR);
        } else if (scale == 160) {
            webView.getSettings().setDefaultZoom(WebSettings.ZoomDensity.MEDIUM);
        } else {
            webView.getSettings().setDefaultZoom(WebSettings.ZoomDensity.CLOSE);
        }
        webView.setWebViewClient(new WebViewClient() {
            // 点击超链接的时候重新在原来进程上加载URL
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                boolean flag = judgeUrl(url);
                if (!flag) {
                    view.loadUrl(url);
                }
                return true;
            }

            @RequiresApi(21)
            @Override
            public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) {
                super.onReceivedHttpError(view, request, errorResponse);
                if(url.equals(StringHelper.convertToString(request.getUrl()))){
                    //请求失败时
                    if (progressDialog != null){
                        progressDialog.dismiss();
                    }
//                    commonLoadErrorLl.setVisibility(View.VISIBLE);
                }else {
                    //请求失败时
                    if (progressDialog != null){
                        progressDialog.dismiss();
                    }
                }
            }


            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
                commonLoadErrorLl.setVisibility(View.GONE);
//                if (progressDialog != null && progressDialog.isShowing()) {
//                    progressDialog.dismiss();
//                }
                progressDialog = CustomProgressDialog.show(activity, "", "正在加载中,请稍候...");
            }

            // webview加载完成
            @Override
            public void onPageFinished(WebView view, String url) {
                if (progressDialog != null)
                    progressDialog.dismiss();
            }

            @Override
            public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
                super.onReceivedError(view, request, error);
                if (progressDialog != null)
                    progressDialog.dismiss();
                commonLoadErrorLl.setVisibility(View.VISIBLE);
            }

        });
        //得到WebSettings对象
        WebSettings settings = webView.getSettings();
        // 获取到UserAgentString
        String userAgent = settings.getUserAgentString();
        // 打印结果
        //listview,webview中滚动拖动到顶部或者底部时的阴影
        webView.setOverScrollMode(View.OVER_SCROLL_NEVER);
        //webView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);//使用缓存
        webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE); //默认不使用缓存!
        webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY); //取消滚动条白边效果
        //webView.setWebChromeClient(new CustomChromeClient("HostApp", HostJsScope.class));
        webView.setWebChromeClient(new MyChromeClient());
        //webView.loadUrl(url);

        StringBuilder builder1 = new StringBuilder();
        try {//拼接post提交参数
            builder1.append("token=").append(token);
        } catch (Exception e) {
            e.printStackTrace();
        }
        String postData = builder1.toString();
        webView.postUrl(url, EncodingUtils.getBytes(postData, "UTF-8"));

//        dialog.setContentView(popView);
//        dialog.setCanceledOnTouchOutside(true);
//        dialog.show();
    }

本文地址:https://blog.csdn.net/dazhong2012/article/details/107946720

相关标签: android开发