如何使用java将八位字节流读取为纯字符串/文本?

lyfkaqu1  于 2021-07-12  发布在  Java
关注(0)|答案(2)|浏览(392)

我有一些来自byte[]的内容,它代表保存到.txt文件的请求的数据。

try {
        while ((bytesRead = streamFromClient.read(currentRequest)) != -1) {

                LOG.info("Received request...");
                addInvoiceRequestOnly();
                streamToServer.write(currentRequest, 0, bytesRead);
                streamToServer.flush();
                dumpTrafficToFile();
            }

        } catch (IOException e) {
            LOG.severe("Could not read/write from/to the request...");
            e.getStackTrace();
        }
POST /domibus/services/...
Host: domibusbackend
Connection: close
Content-Length: 16189
Content-Type: multipart/related; type="application/soap+xml"; boundary="uuid:6b5b42a6-ea2f-4830-84c3-c799f38ca32a"; start="<root.message@cxf.apache.org>"; start-info="application/soap+xml"
Accept: */*
User-Agent: Apache-CXF/3.3.2
Cache-Control: no-cache
Pragma: no-cache
.........
Content-Type: application/octet-stream
Content-Transfer-Encoding: binary
Content-ID: <53c6399c-a6b1-4ffa-9c85-d8b7bb337f28@www.someDomain.com>
CompressionType: application/gzip
MimeType: application/xml

­†’^tÜ:–jq®Z{€Üş˝`cWłÓx˘ěxĐWé"v«8-ňBStÂá›Ë+•jnCćcv‰v2—ťř‘÷ż÷ ĺůéűI˝sJá@Vzľ¸…“ߟ¤Ž2]§yÁbů,m ĺgٱťŠ¸áĐĽ<í.ÖÚeGü®î…Č>
-b¶öG BD,[âŤţ*^lJĘ@DLŃ%Ó:°Ě¸ÉÇVťäś(ăÉÁSy¨±ă“˙řµÁ¨žńˇęÁŽ‚GyvSĄ Ąeě$EI‡*0ĎEĽ•(Ú/{ôđ:d?ćŢ6AgŽ¦ ?ý+𣔣bÁË:˛×í„EQT·
ł/0Ž!ÂŚ6öpqÚ[Q˛ä–ů'0]
ŢfĎgÓŤß7ü–ඤşÔř»?É€“}%ů†Z/€ęŃ·b÷ĂR
żŇ’!|…q· FÉ2ľÎöDÎ>ÖËY)hşk’
łÍĚäŕ„ę+
ă6ţwÇäŘöpŻŞŁ¬tµŢp&ŁK?„8îIč™U\Ä_j)Q“˝QI·čOŽ|ż/Żl±MÁŔµ¤·c{ëŇś¸űXďß%yň¤¨CŇ1ÂĎVÜÝÁwăł[Ť
ťÔ‹Ń(µ[
p]r1Żq{0Ů7ęŐGGżX"˘ćŇÇgj*TRĽĺ*Ă@@ŐÖKąĐ•ľe7­ąWöVĺ:çĂŢnHöT}ł•ť!dĂô¬ZTz'ÝS.¤öX×čÜť9Ü°™ô-Ue#xÚ–LL‡
í
‹Uĺ×Tśü«$tĚ

有人能告诉我如何把这些数据转换成可读的数据吗?它在头中说,它应该是二进制的,但它不是,二进制数据看起来不同。我从请求中得到了很多可读的数据,但最后一部分,你看到的是外星人的东西,我不知道如何解码它。。。如果有人能帮我,我会很感激的。谢谢您!

zphenhs4

zphenhs41#

这表明压缩: CompressionType: application/gzip 所以将body馈送到java.util.zip.gzip输入流中

oknwwptz

oknwwptz2#

我猜你在用 Servlet-API 如果您使用的是任何框架,则需要修改第一个代码段以提取请求主体并将其传递给 extract() .

public void doPost(HttpServletRequest request, HttpServletResponse response) {
    InflaterInputStream is = InflaterInputStream(request.getInputStream()); 
    String readableString = extract(is);
    // do the processing
}

然后将压缩的二进制数据转换成可读的字符串

private String extract(InputStream is) throws IOException {
    StringBuffer sb = new StringBuffer();
    BufferedReader in = new BufferedReader(new InputStreamReader(is));
    String inputLine = "";
    while ((inputLine = in.readLine()) != null) {
        sb.append(inputLine);
    }
    return sb.toString();
}

相关问题