BufferedReader未读取请求正文

时间:2018-08-04 04:20:32

标签: java server client bufferedreader

我正在尝试从HttpPost读取数据,但是当我从BufferedReader读取数据时,我仅获得标头信息。请参见下面的代码。

这是服务器

     for (int i=0; i<3; i++)
            {
             resume:
                for (……………)
                          {
                                 ……..
                              if (……..) break resume;
                 }
    }

这是客户

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

但是我不知道为什么。请帮助我整天被困住。

预先感谢

2 个答案:

答案 0 :(得分:1)

  

但是我不知道为什么。

您的服务器将从null获取buffer.readLine()的唯一方法是客户端关闭其套接字输出流。

问题是客户端正在尝试保持连接活动……这意味着它将不会关闭其套接字输出流。这意味着服务器需要遵守“ content-length”标头;即计算读取的字节数,而不是查找流的结尾。

从根本上讲,您的服务器端未正确实现HTTP 1.1规范。

该怎么办?好吧,我的建议是不要尝试从套接字开始实现HTTP。使用和现有的框架...或Apache HttpComponents库。但是,如果您坚持要这样做 1 ,请在开始尝试实现之前先通读HTTP规范


1-定义:受虐狂-享受似乎痛苦或乏味的活动。

答案 1 :(得分:-1)

在您的while循环中使用!= 0而不是!= null:

while((line = buffer.readLine()).length() !=0) {

输出:

  

端口8332读取:POST / HTTP / 1.1内容类型:   application / x-www-form-urlencodedContent-Length:18主机:   本地主机:8332连接:Keep-AliveUser-Agent:   Apache-HttpClient / 4.5.3(Java / 1.8.0_171)接受编码:   gzip,deflateorg.apache.http.NoHttpResponseException:本地主机:8332   无法回应

相关问题