【问题标题】:POST data via CustomTab or Chrome通过 CustomTab 或 Chrome 发布数据
【发布时间】:2017-11-12 00:46:12
【问题描述】:

我想通过 CustomTab 或 Chrome 发送 POST HTTP 请求,然后最终显示页面。我做了很多研究,但没有办法。 有办法吗? 可以通过 Volley 发送 POST 请求,然后最终在浏览器中显示响应吗?

【问题讨论】:

标签: java android android-volley chrome-custom-tabs android-customtabs


【解决方案1】:

我为此写了一个解决方法。

小心点,很脏;)

步骤:

  • 您需要创建一个包含表单的 html 文件
  • 向其中添加与您需要传递给您的 url 的值相对应的输入字段
  • 将此文件添加到您的资产文件夹中
  • 关于安卓代码:
    • 读取文件内容
    • 将内容保存到外部缓存目录
    • >>此步骤非常基础从现在开始遵循这些说明(@Skotos 关于如何使用自定义选项卡意图打开本地 html 的回答 https://stackoverflow.com/a/60078339/2124387

示例:

这是我在 assets 文件夹中名为 form_template.html 的 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://stackoverflow.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();
    }

【讨论】:

  • 非常感谢.. 虽然由于表单提交而有 1 秒的延迟,但除此之外它工作得很好。还要确保 {{fields}} 应替换为具有正确 id、名称和值的 标签
猜你喜欢
  • 1970-01-01
  • 2012-04-30
  • 1970-01-01
  • 2012-08-01
  • 1970-01-01
  • 2013-10-17
  • 1970-01-01
  • 1970-01-01
  • 2020-04-19
相关资源
最近更新 更多