服务器
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();
}
}
客户端
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();
}
}
对此有何想法?这就是我回来的全部内容,只是标题:
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();
}
答案 0 :(得分:1)
根据我的理解,做了一些阅读之后,BufferedReader是一种从http post读取inputStreams的坏方法。我所经历的是,发布帖子的客户端会挂起,所以每个帖子上的连接处理程序线程是什么,当我杀死客户端时,服务器会停止挂起,我会看到消息体。根据我在互联网上收集的信息,读取输入流的最佳方法是逐字节逐步执行,并在字节总和==内容长度值后退出循环。
那就是说,我打算使用Apache HTTPCore来处理这个,因为这似乎是一个更好的解决方案
答案 1 :(得分:0)
值得一提的是,如果有人像我一样来到这里,这就是我写的
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];
}