I have a simple HTTP server that must manually implement handling for POST requests that send in a file. The problem is, if the header does not include an Expect: 100-continue and thus sends the HTTP body along with the headers, when I call DataInputStream.readFully() to read, there's no data to be read and it blocks indefinitely.
I make the POST request via cURL: curl "localhost:40000/test1.txt" --data-binary @./test.txt --trace dump, sending a small text file containing only hello world in it.
private static void postRequest(InputStream input, OutputStream output, BufferedReader reader, String fileName) throws IOException {
var dataInput = new DataInputStream(input);
String line;
byte[] byteArray = new byte[0];
int length = 0;
var writer = new BufferedWriter(new OutputStreamWriter(output));
while ((line = reader.readLine()) != null && !line.isEmpty()) {
String[] split = line.split(" ");
if (split[0].equals("Content-Length:")) {
length = Integer.parseInt(split[1]);
byteArray = new byte[length];
} else if (line.equals("Expect: 100-continue")) {
writer.write(CONTINUE_HEADER); // HTTP/1.1 100 Continue
writer.flush();
}
System.out.println(line);
}
System.out.println(line);
writeToFile(fileName, dataInput, byteArray, length, writer);
}
private static void writeToFile(String fileName, DataInputStream dataInput, byte[] byteArray, int length, BufferedWriter writer) throws IOException {
dataInput.readFully(byteArray, 0, length);
try (var stream = new FileOutputStream(fileName)) {
stream.write(byteArray);
System.out.println("File successfully saved to server.");
} catch (IOException e) {
System.out.println("Could not write to file.");
writer.write(INTERNAL_SERVICE_ERROR_HEADER);
}
writer.write(CREATED_HEADER);
}
I've tried calling DataInputStream.available() right before calling readFully(), and it always returns 0. Calling BufferedReader.ready() returns false if there's an Expect: 100-continue, but true otherwise. However, it still doesn't have any data to read.