このコードを実行すると、最後の while ループで OutputStream.write で例外が発生します (コード内の他の場所では正常に動作します)。コンテンツの長さとブラウザへの結果の転送は機能しますが、「Transfer-Encoding: chunked」ポリシーを処理しようとすると、同じメソッドは機能せず、次の例外がスローされます。
java.net.SocketException: Connection reset by peer: socket write error
at java.net.SocketOutputStream.socketWrite0(Native Method)
at java.net.SocketOutputStream.socketWrite(Unknown Source)
at java.net.SocketOutputStream.write(Unknown Source)
at IncomingRequest.run(IncomingRequest.java:250)
is = hostSocket.getInputStream();
OutputStream os = client.getOutputStream();
System.out.println("Forwarding request from server");
byte[] currByte = new byte[1];
StringBuilder responseHeader = new StringBuilder();
int crlfCounter = 4;
// Separates the response header by looking for 2 consecutive \r\n
while (crlfCounter > 0){
is.read(currByte);
os.write(currByte);
System.out.print((char)currByte[0]);
responseHeader.append((char)currByte[0]);
if ((char)currByte[0] == '\r' || (char)currByte[0] == '\n'){
crlfCounter--;
}else{
crlfCounter = 4;
}
}
StringBuilder chuckSize = new StringBuilder();
int contentLength = 0;
int contentIndex = responseHeader.toString().indexOf("Content-Length: ");
int chunkedIndex = responseHeader.toString().indexOf("Transfer-Encoding: chunked");
if (contentIndex != -1) {
contentIndex += 16;
int conEnd = responseHeader.toString().indexOf('\n', contentIndex);
contentLength = Integer.parseInt(responseHeader.toString().substring(contentIndex,conEnd).trim());
System.out.println("Content Length is : " + contentLength);
while (contentLength > 0){
is.read(currByte);
os.write(currByte);
contentLength--;
}
os.write('\r');
os.write('\n');
os.write('\r');
os.write('\n');
} else if (chunkedIndex != -1){
boolean lastChunk = false;
while (!lastChunk) {
do {
is.read(currByte);
chuckSize.append((char) currByte[0]);
} while ((char)currByte[0] != '\n');
contentLength = Integer.parseInt(chuckSize.toString().trim(), 16);
System.out.println("Hex " + chuckSize.toString());
System.out.println(contentLength + " the number");
if (contentLength == 0) {
lastChunk = true;
}
while (contentLength > 0){
is.read(currByte);
os.write(currByte);
contentLength--;
}
}
}