【发布时间】:2018-08-04 04:20:32
【问题描述】:
我正在尝试从 HttpPost 读取数据,但是当我从 BufferedReader 读取数据时,我只能获得标题信息。请看下面的代码。
这是服务器
try {
ServerSocket server = new ServerSocket(8332);
System.out.println("Listening for connection on port 8332 ....");
while (true) {
try (Socket socket = server.accept()) {
BufferedReader buffer = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String request = "";
String line;
while ((line = buffer.readLine()) != null) {
System.out.println(line);
request += line;
}
System.out.print("port 8332 reading: " + request);
} catch (IOException e) {
System.out.print(e.getMessage());
}
}
} catch (IOException e){
System.out.print(e.getMessage());
}
这里是客户端
HttpClient client = HttpClientBuilder.create().build();
HttpPost post = new HttpPost("http://localhost:8332");
try {
StringEntity params =new StringEntity("details={\"name\":\"myname\",\"age\":\"20\"} ");
post.addHeader("content-type", "application/x-www-form-urlencoded");
post.setEntity(params);
client.execute(post);
} catch (IOException e){
System.out.println(e);
}
当我运行这个程序时,我只会得到以下输出
Listening for connection on port 8332 ....
POST / HTTP/1.1
content-type: application/x-www-form-urlencoded
Content-Length: 37
Host: localhost:8332
Connection: Keep-Alive
User-Agent: Apache-HttpClient/4.5.6 (Java/1.8.0_131)
Accept-Encoding: gzip,deflate
在调试时,程序似乎没有退出这个 while 循环
while ((line = buffer.readLine()) != null) {
System.out.println(line);
request += line;
}
但我不知道为什么。请帮助我一整天都被卡住了。
提前致谢
【问题讨论】:
标签: java server client bufferedreader