POST data via CustomTab or Chrome
Asked Answered
M

1

8

I want send POST HTTP request via CustomTab or Chrome then show page finally. I many research but no way for it. is there a way? can send POST request via Volley then show response in browser finally?

Munch answered 9/6, 2017 at 22:2 Comment(2)
no way really? :(Munch
Even on desktop, there's no way to day this. See #4798034.Contemplative
M
7

I wrote a workaround for that.

Careful, is a dirty one ;)

Steps:

Example:

this is my html file called form_template.html in the assets folder:

    <html>
        <script>
            function submitForm() {
                document.getElementById("form").submit()
            }
        </script>

        <body onload="submitForm()">
            <form id="form" action="{{url}}" method="{{method}}" enctype="{{enctype}}">
                {{fields}}
            </form>
        </body>
    </html>

end this is how i pass dynamically url and values to it

    Map<String, String> values = ImmutableMap.of(
        "fooKey", "fooValue", // whatever you
        "barKey", "barValue"  // need here
    );

    try {
        File redirect = new File(activity.getExternalCacheDir(), "redirect.html");

        // To get string from input stream look at here https://mcmap.net/q/277643/-read-assets-file-as-string
        String templateString = getStringFromInputStream(activity.getAssets().open("form_template.html"));

        List<String> inputFields = new ArrayList<>();
        for (String key : values.keySet()) {
            inputFields.add(String.format("<input type=\"hidden\" name=\"%s\" value=\"%s\" />", key, values.get(key)));
        }

        templateString = templateString.replace("{{url}}", url);
        templateString = templateString.replace("{{method}}", method); // eg. "POST"
        templateString = templateString.replace("{{enctype}}", encodeType); // eg. "application/x-www-form-urlencoded"
        templateString = templateString.replace("{{fields}}", StringUtil.join("\n", inputFields));

        FileOutputStream fileOutputStream = new FileOutputStream(redirect);
        fileOutputStream.write(templateString.getBytes());
        Uri uri = FileProvider.getUriForFile(activity, BuildConfig.ApplicationId + ".provider", redirect);
        new Handler().postDelayed(redirect::delete, 5000);

        CustomTabsIntent.Builder builder = new CustomTabsIntent.Builder();
        CustomTabsIntent customTabsIntent = builder.build();
        customTabsIntent.intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION))
        customTabsIntent.launchUrl(this, packageName, url);
    } catch (IOException e) {
        e.printStackTrace();
    }
Mordancy answered 23/4, 2020 at 22:43 Comment(1)
Thanks a ton.. although there was 1sec lag due to form submission, apart from that it worked great. Also just make sure that {{fields}} should be replaced by the <input/> tags with proper id, name and valueCondign

© 2022 - 2024 — McMap. All rights reserved.