InputStream을 사용하여 HTTP 요청을 읽는 방법은 무엇입니까? 나는이처럼 읽는 데 사용 : null
라인에 도달 할 것이라는 보장이 없기 때문에 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()
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'을 반환합니다. 따라서 연결이 닫히면 마지막 줄을 읽은 후 null이 반환됩니다. –
내가 도달 할 수있는 첫 번째 null 줄은 머리글과 머리글 사이의 구분 기호로 양식 데이터와 같습니다. 그러나 시체 뒤에 null 줄이 없습니다. 뭐라구? – Tony
빈 몸으로 요청을받을 수 있습니까? –