Reputation: 4220
server
public void HandleConnection(Socket socket) {
OutputStream out = socket.getOutputStream();
InputStream in = socket.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
try {
while ((strLine = br.readLine()) != null) {
System.out.println (strLine);
}
} catch (IOException e) {
e.printStackTrace();
}
}
client
public void httpPostTest() {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://192.168.0.2:8080/");
try {
httppost.setEntity(new StringEntity("test"));
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Any thoughts on this? This is all I get back, just the header:
POST / HTTP/1.1
Content-Length: 4
Content-Type: text/plain; charset=ISO-8859-1
Host: 192.168.0.2:8080
Connection: Keep-Alive
User-Agent: Apache-HttpClient/4.1.2 (java 1.5)
public String readLine(InputStream inputStream) {
StringWriter writer = new StringWriter();
try {
IOUtils.copy(inputStream, writer, "ASCII");
} catch (IOException e) {
e.printStackTrace();
}
String theString = writer.toString();
return theString.trim();
}
Upvotes: 1
Views: 2766
Reputation: 2022
For whats worth, if someone comes here like me, here's what I wrote
InputStream stream = socket.getInputStream();
byte[] b = new byte[1024];
while(stream.read(b) > 0 && !socket.isInputShutdown()) {
System.out.println(new String(b));
b = null;
b = new byte[1024];
}
Upvotes: 0
Reputation: 4220
From what I understand after doing some reading, BufferedReader is a bad way to read inputStreams from http post. What I was experiencing was that the client making the post would hang and so what the connection handler thread on every post, when I would kill the client the server would stop hanging and I would see the message body. From what I gathered on the internet, the best way to read the input stream is to step through it byte by byte, and exit the loop after the sum of the bytes == the content-length value.
That said, I'm planning on using Apache HTTPCore instead to handle this as that seems like a better solution
Upvotes: 1