我需要通过 Play Framework 在 GET 请求中获取二进制数据。这用于从 BitTorrent 客户端获取 info_hash。
我是这样理解的:
byte[] infoHash = params.get("info_hash").getBytes("ISO-8859-1")
不幸的是,所有非 ascii 符号都被 0x3f 替换了。
附言我可以从 Http.Request.current().querystring 获取 url 编码的参数,但这是个坏主意。
更新:我用我的变体覆盖了 play.data.parsing.UrlEncodedParser.parse(InputStream is)
方法,在参数中使用了 ISO-8859-1 而不是硬编码UTF-8 与原始格式一样,一切正常。但我仍在寻找更好的方法,因为我不想编辑框架源。
最佳答案
根据 http://wiki.theory.org/BitTorrent_Tracker_Protocol :
info_hash
The 20 byte sha1 hash of the bencoded form of the info value from the metainfo file.
SHA1 和如下所示:92a11182a8405cbd8d25cd3cc3334fc6155bec06
字节表示中的每一对连续的字节。尽管此表示本身可能已编码,但它不是 info_hash 字节的 URL 编码。
因此您需要将字符串中的每对字符转换为一个字节。如果你找到一个图书馆代替它,坚持下去。如果没有,请随意使用此代码:
byte[] decode(String enc) {
if (enc.length() % 2 != 0) throw new NumberFormatException();
byte arr[] = new byte[enc.length() / 2];
int c = 0;
for (int i = 0; i < enc.length(); i += 2) {
arr[c++] = Integer.valueOf(enc.substring(i, i + 2), 16).byteValue();
}
return arr;
}
关于java - 在 Play Framework 中获取二进制 HTTP GET 参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4880900/