如何使用InputStream读取HTTP请求?我用这样来阅读:如何正确读取http请求?
InputStream in = address.openStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder result = new StringBuilder();
String line;
while((line = reader.readLine()) != null) {
result.append(line);
}
System.out.println(result.toString());
但reader.readLine()
可能被阻止,因为没有保证null
线将到达。当然,我可以读Content-Length头,然后在一个循环中读取请求:
for (int i = 0; i < contentLength; i++) {
int a = br.read();
body.append((char) a);
}
但如果内容长度设置得过大(我想这可以手动设置目的),br.read()
将被阻止。 我尝试从InputStream中像这样直接读取的字节:
byte[] bytes = getBytes(is);
public static byte[] getBytes(InputStream is) throws IOException {
int len;
int size = 1024;
byte[] buf;
if (is instanceof ByteArrayInputStream) {
size = is.available();
buf = new byte[size];
len = is.read(buf, 0, size);
} else {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
buf = new byte[size];
while ((len = is.read(buf, 0, size)) != -1)
bos.write(buf, 0, len);
buf = bos.toByteArray();
}
return buf;
}
但它永远等待。做什么?
为什么不能保证能够达到'null'行?根据文档,如果已经到达流的末尾,它将返回'null'。所以如果连接被关闭,你会在读完最后一行后得到空值。 –
我可以达到的第一个空行是头和请求体之间的分隔符(如表单数据)。但身体后面没有空线。做什么? – Tony
也许你得到一个空的身体请求? –