Данные POST через CustomTab или Chrome

Я хочу отправить HTTP-запрос POST через CustomTab или Chrome, а затем показать страницу, наконец. Я много исследований, но нет пути для этого. есть ли способ? Можно отправить запрос POST через Volley, а затем показать ответ в браузере, наконец?

0 ответов

Я написал обходной путь для этого.

Осторожно, грязно;)

Шаги:

  • вам нужно создать html файл с формой внутри него
  • добавьте в него поля ввода, соответствующие значениям, которые вам нужно передать на свой URL
  • добавьте этот файл в папку с ресурсами
  • в коде Android:

Пример:

это мой html файл под названием form_template.html в папке с ресурсами:

    <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>

конец вот как я передаю ему динамически URL и значения

    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://stackru.com/a/16110044/2124387
        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();
    }
Другие вопросы по тегам