WebView 中 post 的 Base64 编码

Base64 encoding for post in WebView

我遇到了字符串编码问题。首先,让我解释一下上下文:

我需要制作一个 post 并将内容加载到 webView 中。对于这个要求,我需要使用 webView.postUrl(String url, byte[] postData).

我看到很多使用此方法的示例以及 EncodingUtils.getBytes("stringToEncode","base64")。

好消息是这对我有用。坏消息是此 class 已弃用,您需要将下一个代码添加到 gradle 文件:

android {
    useLibrary 'org.apache.http.legacy'
}

我想避免这种情况并使用它应该的方式。

据我所知,这个已弃用的 class 的替代品是 android.util.Base64.

我尝试了下一个代码但没有成功:

webView.postUrl("url", Base64.encode("paramsToEncode".getBytes(),Base64.DEFAULT));

webView.postUrl("url", Base64.encode("paramsToEncode".getBytes(StandardCharsets.UTF_8),Base64.DEFAULT));

根据EncodingUtils的文档:

Converts the specified string to a byte array. If the charset is not supported the default system charset is used. Parameters: data - the string to be encoded charset - the desired character encoding Returns: The resulting byte array.

以及 Base64 的文档:

input byte: the data to encode flags int: controls certain features of the encoded output. Passing DEFAULT results in output that adheres to RFC 2045. Returns byte[]

所以我不知道我做错了什么。如果您遇到此类问题,我将不胜感激 :).

不确定为什么您的示例不起作用,但下面的代码似乎对我有用:

webView.postUrl(url, urlParams.getBytes(Charset.forName("UTF-8")));