Android - how to intercept a form POST in android WebViewClient on API level 4

十年热恋 提交于 2019-11-27 07:48:44

This is known issue, that shouldOverrideUrlLoading don't catch POST. See http://code.google.com/p/android/issues/detail?id=9122 for details.

Use GET! I personally tried using POST, because I expected some limitation of GET parameters (i.e. length of URL), but I just successfully passed 32000 bytes through GET locally without any problems.

Do you really need to use a POST? If you want to handle formdata locally, why not have a piece of javascript handle your form and interface with "native" java code using addJavascriptInterface. E.g.

WebView engine = (WebView) findViewById(R.id.web_engine);       
engine.getSettings().setJavaScriptEnabled(true); 
engine.addJavascriptInterface(new MyBridge(this), "bridge");
engine.loadUrl(...)

Your bridge can be any class basically and you should be able to access its methods directly from javascript. E.g.

public class MyBridge {

    public MyBridge(Context context) {
         // ...
    }

    public String doIt(String a, String b) {
            JSONArray result = new JSONArray();
            result.put("Hello " + a);
            result.put("Hello " + b);
            return result.toString();       
    }

Your html / javascript could look like:

<script type="text/javascript">
    $("#button").click(function() {
        var a = $("#a").val();
        var b = $("#b").val();

        var result=JSON.parse(bridge.doIt(a, b));
        // ...
    }
</script>

<input id="a"><input id="b"><button id="button">click</button>
wangzhengyi

I think you can override onLoadResource(WebView view, String url) from WebViewClient. This function is Added in API LEVEL 1.

This function is called when WebView will load the resource specified by the given url. Resource include js, css, iframe embeded url. Code example like this:

    @Override
    public void onLoadResource(WebView view, String url) {
        if (url.indexOf("http://www.example.com") != -1 && view != null) {
            // open url in default browser
            view.stopLoading();
            view.getContext().startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
        }
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!