无法在webview中加载相同的网页两次

时间:2018-01-24 15:29:25

标签: android json android-layout webview

我有一个webview我正在加载一个urlpostrequest的授权标题,当我第一次加载webview时我会尝试显示网页再次打开同一页面我无法得到任何错误或输出。以下是我的webviewActivity

public class JavaWebviewActivity extends AppCompatActivity {

    WebView webView;
    ProgressBar progressBar;
    VolleyService services;
    String link, firstId, thirdId, secondId;
    private ValueCallback<Uri[]> mUploadMessage;
    private final static int FILECHOOSER_RESULTCODE = 1;

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

        webView = findViewById(R.id.mWebView);
        progressBar = findViewById(R.id.progressBar);
        services = new VolleyService();
        services.intialise(this);

        Intent intent = getIntent();
        link = intent.getStringExtra(getString(R.string.link));
        firstId = intent.getStringExtra(getString(R.string.courseId));
        secondId = intent.getStringExtra(getString(R.string.moduleId));
        thirdId = intent.getStringExtra(getString(R.string.completionId));

        webView.setWebViewClient(new WebViewClient() {
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return false;
            }

            @Override
            public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
                super.onReceivedError(view, request, error);
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
                progressBar.setVisibility(View.VISIBLE);
                webView.setVisibility(View.GONE);
            }

            @Override
            public void onPageCommitVisible(WebView view, String url) {
                super.onPageCommitVisible(view, url);
                progressBar.setVisibility(View.GONE);
                webView.setVisibility(View.VISIBLE);
            }
        });
        webView.setWebChromeClient(new MyWebChromeClient());

        webView.getSettings().setJavaScriptEnabled(true);
        webView.getSettings().setAllowFileAccess(true);
        webView.setVerticalScrollBarEnabled(true);
        webView.getSettings().setDomStorageEnabled(true);
        webView.setHorizontalScrollBarEnabled(true);
        webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
        webView.getSettings().setUseWideViewPort(true);
        webView.getSettings().setAllowFileAccessFromFileURLs(true);
        webView.getSettings().setAllowUniversalAccessFromFileURLs(true);
        String postData = "first_id=" + firstId + "&second_id=" + secondId + "&third_id=" + thirdId;
        postURL(link, postData);
    }

    class MyWebChromeClient extends WebChromeClient {

        @Override
        public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
            super.onShowFileChooser(webView, filePathCallback, fileChooserParams);
            mUploadMessage = filePathCallback;
            openFileChooser(filePathCallback);
            return true;
        }

        @Override
        public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
            System.out.println("console  errors are "+consoleMessage);
            return super.onConsoleMessage(consoleMessage);
        }

        @Override
        public boolean onJsPrompt(WebView view, String url, String message, String defaultValue, JsPromptResult result) {
            return super.onJsPrompt(view, url, message, defaultValue, result);
        }

        @Override
        public boolean onJsAlert(WebView view, String url, final String message, JsResult result) {
            System.out.println("message is " + message);
            if (message.equalsIgnoreCase("close") || message.equalsIgnoreCase("true")) {
                onBackPressed();
            } else {
                Thread thread = new Thread(new Runnable() {
                    @Override
                    public void run() {
                        services.downLoadFile(JavaWebviewActivity.this, message);
                    }
                });
                thread.start();
            }

            return true;
        }

        private void openFileChooser(ValueCallback<Uri[]> uploadMsg) {
            Intent i = new Intent(Intent.ACTION_GET_CONTENT);
            i.addCategory(Intent.CATEGORY_OPENABLE);
            i.setType("*/*");
            JavaWebviewActivity.this.startActivityForResult(
                    Intent.createChooser(i, "File Browser"),
                    FILECHOOSER_RESULTCODE);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode,
                                    Intent intent) {
        if (requestCode == FILECHOOSER_RESULTCODE) {
            Uri result = intent == null || resultCode != RESULT_OK ? null
                    : intent.getData();
            Uri[] resultsArray = new Uri[1];
            resultsArray[0] = result;
            mUploadMessage.onReceiveValue(resultsArray);
            System.out.println("success " + result.getPath());
        }
    }

    protected void postURL(final String url, String postData) {
        Request request = new Request.Builder()
                .url(url)
                .addHeader("Authorization", services.prefs.getString(getString(R.string.token_type), "") + " " + services.prefs.getString(getString(R.string.access_token), ""))
                .addHeader("Content-Type", "application/json")
                .post(RequestBody.create(MediaType.parse("application/x-www-form-urlencoded"), postData))
                .build();

        System.out.println("request headers are "+request.headers());

        OkHttpClient object = new OkHttpClient();
        object.newCall(request).enqueue(new Callback() {

            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {

            }

            @Override
            public void onResponse(@NonNull Call call, Response response) throws IOException {
                final String htmlString = response.body().string();
                webView.post(new Runnable() {
                    @Override
                    public void run() {
                        webView.clearCache(true);
                        webView.loadDataWithBaseURL(url, htmlString, "text/html", "utf-8", null);
                    }
                });
            }
        });
    }
}

还共享我的XML文件的代码:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <include
        android:id="@+id/tbWebView"
        android:visibility="gone"
        layout="@layout/toolbar" />

    <ProgressBar
        android:id="@+id/progressBar"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:layout_gravity="center"
        android:background="@android:color/transparent"
        android:visibility="gone" />

    <WebView
        android:id="@+id/mWebView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@+id/tbWebView" />

</RelativeLayout>

0 个答案:

没有答案