以多种格式从InputStream读取 [英] Read from InputStream in multiple formats

查看:218
本文介绍了以多种格式从InputStream读取的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个读取HTTP请求和响应并解析它们的类。
由于标题是普通文本,因此使用 BufferedReader readLine 方法阅读它们似乎最简单。这显然不适用于数据体,因为它可能是二进制的,所以我想在读取标题后切换到读取原始字节。

I'm trying to write a class that reads HTTP requests and responses and parses them. Since the headers are ordinary text it seemed easiest to read them using a BufferedReader and the readLine method. This obviously won't do for the data body as it may be binary, so I want to switch over to read raw bytes after the headers have been read.

现在,我正在做这样的事情:

Right now, I'm doing something like this:

InputStream input=socket.getInputStream();
BufferedReader reader=new BufferedReader(new InputStreamReader(input));
BufferedInputStream binstream=new BufferedInputStream(input);

问题是 BufferedReader 正在提前阅读并吞噬所有在我有机会通过binstream获取它之前来自流的二进制数据。

The problem is that the BufferedReader is reading ahead and gobbling up all the binary data from the stream before I have a chance to get at it with the binstream.

有没有办法阻止它在每次调用<强>的readLine
或者有更好的方法来读取原始二进制数据后的单行ASCII文本吗?

Is there a way to prevent it from reading beyond the newline for each call to readLine? Or is there a better way to read single lines of ASCII text followed raw binary data?

推荐答案

已经有了Java中用于处理HTTP请求和响应的类。您应该使用它而不是尝试自己解析响应。解析HTTP响应比您想象的更困难,因为您必须处理不同的编码方法。它不是响应有效负载中的原始二进制数据。 HttpURLConnection类将为您解析标头,并为有效负载提供InputStream。

There is already a class in Java for handling HTTP requests and responses. You should use that instead of trying to parse the response on your own. Parsing HTTP response is more difficult than you think as there are different encoding methods that you have to deal with. It isn't really raw binary data in the response payload. The HttpURLConnection class will parse headers for you and give you InputStream for the payload.

http://download.oracle.com/javase/1.4.2/docs/api/java/net/HttpURLConnection.html

这篇关于以多种格式从InputStream读取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆