Skip to content Skip to sidebar Skip to footer

Post Data Via Customtab Or Chrome

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

Solution 1:

I wrote a workaround for that.

Careful, is a dirty one ;)

Steps:

  • you need to create an html file with a form inside it
  • add input fields to it corresponding to the values you need to pass to your url
  • add this file to your asset folder
  • on android code:
    • read the content of the file
    • save the content to the external cache directory
    • >>THIS STEP IS FUNDAMENTAL<< from now on follow these instructions (@Skotos's answer on how to open a local html with a custom tab intent https://stackoverflow.com/a/60078339/2124387)

Example:

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

<html><script>functionsubmitForm() {
                document.getElementById("form").submit()
            }
        </script><bodyonload="submitForm()"><formid="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 = newFile(activity.getExternalCacheDir(), "redirect.html");

        // To get string from input stream look at here https://stackoverflow.com/a/16110044/2124387String templateString = getStringFromInputStream(activity.getAssets().open("form_template.html"));

        List<String> inputFields = newArrayList<>();
        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 = newFileOutputStream(redirect);
        fileOutputStream.write(templateString.getBytes());
        Uri uri = FileProvider.getUriForFile(activity, BuildConfig.ApplicationId + ".provider", redirect);
        newHandler().postDelayed(redirect::delete, 5000);

        CustomTabsIntent.Builder builder = newCustomTabsIntent.Builder();
        CustomTabsIntent customTabsIntent = builder.build();
        customTabsIntent.intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION))
        customTabsIntent.launchUrl(this, packageName, url);
    } catch (IOException e) {
        e.printStackTrace();
    }

Post a Comment for "Post Data Via Customtab Or Chrome"