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

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

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

  1. try {
  2. while ((bytesRead = streamFromClient.read(currentRequest)) != -1) {
  3. LOG.info("Received request...");
  4. addInvoiceRequestOnly();
  5. streamToServer.write(currentRequest, 0, bytesRead);
  6. streamToServer.flush();
  7. dumpTrafficToFile();
  8. }
  9. } catch (IOException e) {
  10. LOG.severe("Could not read/write from/to the request...");
  11. e.getStackTrace();
  12. }
  1. POST /domibus/services/...
  2. Host: domibusbackend
  3. Connection: close
  4. Content-Length: 16189
  5. 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"
  6. Accept: */*
  7. User-Agent: Apache-CXF/3.3.2
  8. Cache-Control: no-cache
  9. Pragma: no-cache
  1. .........
  1. Content-Type: application/octet-stream
  2. Content-Transfer-Encoding: binary
  3. Content-ID: <53c6399c-a6b1-4ffa-9c85-d8b7bb337f28@www.someDomain.com>
  4. CompressionType: application/gzip
  5. MimeType: application/xml
  6. ­†’^tÜ:–jq®Z{€Üş˝`cWłÓx˘ěxĐWé"v«8-ňBStÂá›Ë+•jnCćcv‰v2—ťř‘÷ż÷ ĺůéűI˝sJá@Vzľ¸…“ߟ¤Ž2]§yÁbů,m ĺgٱťŠ¸áĐĽ<í.ÖÚeGü®î…Č>
  7. -b¶öG BD,[âŤţ*^lJĘ@DLŃ%Ó:°Ě¸ÉÇVťäś(ăÉÁSy¨±ă“˙řµÁ¨žńˇęÁŽ‚GyvSĄ Ąeě$EI‡*0ĎEĽ•(Ú/{ôđ:d?ćŢ6Agަ ?ý+𣔣bÁË:˛×í„EQT·
  8. ł/0Ž!ÂŚ6öpqÚ[Q˛ä–ů'0]
  9. ŢfĎgÓŤß7ü–ඤşÔř»?É€“}%ů†Z/€ęŃ·b÷ĂR
  10. żŇ’!|…q· FÉ2ľÎöDÎ>ÖËY)hşk’
  11. łÍĚäŕ„ę+
  12. ă6ţwÇäŘöpŻŞŁ¬tµŢp&ŁK?„8îIč™U\Ä_j)Q“˝QI·čOŽ|ż/Żl±MÁŔµ¤·c{ëŇś¸űXďß%yň¤¨CŇ1ÂĎVÜÝÁwăł[Ť
  13. ťÔ‹Ń(µ[
  14. p]r1Żq{0Ů7ęŐGGżX"˘ćŇÇgj*TRĽĺ*Ă@@ŐÖKąĐ•ľe7­ąWöVĺ:çĂŢnHöT}ł•ť!dĂô¬ZTz'ÝS.¤öX×čÜť9ܰ™ô-Ue#xÚ–LL‡
  15. í
  16. ‹Uĺ×Tśü«$tĚ

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

zphenhs4

zphenhs41#

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

oknwwptz

oknwwptz2#

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

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

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

  1. private String extract(InputStream is) throws IOException {
  2. StringBuffer sb = new StringBuffer();
  3. BufferedReader in = new BufferedReader(new InputStreamReader(is));
  4. String inputLine = "";
  5. while ((inputLine = in.readLine()) != null) {
  6. sb.append(inputLine);
  7. }
  8. return sb.toString();
  9. }
展开查看全部

相关问题