Reputation: 2470
I have an HTML form that makes a POST request to a Socket I made with Java. I read each line with
/**
* Read a line from an {@link InputStream}
* @param inFromClient The {@link InputStream} to read from
* @return The {@link String} read
* @throws IOException When something went wrong while reading
*/
private String readLine(InputStream inFromClient) throws IOException {
StringBuilder lineb = new StringBuilder();
char c = (char) inFromClient.read();
while (c != '\n'){
lineb.append(Character.toString(c));
c = (char) (inFromClient.read());
}
String line = lineb.toString();
return line.substring(0,line.lastIndexOf('\r')<0?0:line.lastIndexOf('\r'));
}
That way, I'm able to parse the request till the boundary and then save the file sent. Everything works perfectly.
However, I'm also trying to make a POST request with Java to the same socket. First, I create a second socket connected to my server socket. Then I do:
PrintWriter pw = new PrintWriter(socket.getOutputStream(), true);
pw.println("POST / HTTP/1.1");
pw.println("Host: ...");
...
The problem is, my method cannot read any line and it all ends up with a "OutOfMemory' exception at line 5. Why am I not able to read lines sent from a Java socket while I can read those sent from my browser (html form) ? Thank you.
Upvotes: 0
Views: 199
Reputation: 1919
Your server code must read() into an int and check whether that's -1 before casting to a char. You're ignoring end-of-file from the stream and appending -1 to your string builder for ever.
However:
I'd recommend using an existing HTTP server framework in your server to read and parse requests, rather than writing your own. (Or at least use an off-the-shelf HTTP request parser / response serialiser if you want to use your own socket code.)
Both your client and server code ignore character encoding. You need to convert bytes to/from chars using a Charset instance.
Use HttpURLConnection in your client, rather than a simple TCP socket.
Better, use something like https://hc.apache.org/ for your HTTP functionality.
Upvotes: 1