如何修复此方法以不丢失JSON字符串

时间:2013-07-03 01:28:04

标签: java http

这听起来很奇怪,但这种方法适用于获取/大多数POST请求,但有时(通常最近)StringBuffer不会捕获http请求(JSON)末尾附加的数据。我哪里错了?

/**
     * Parses a client request and calls the appropriate handler
     * @throws Exception
     */
    private void processClientRequest() throws Exception{

        //Get the client request
        BufferedReader clientRequest = new BufferedReader(new InputStreamReader(connectedClient.getInputStream()));

        //Start response object
        DataOutputStream responseToClient = new DataOutputStream(connectedClient.getOutputStream());

        System.out.println(clientRequest);
        String requestString = clientRequest.readLine();

        String header = requestString;

        //Break up request
        StringTokenizer tokenizer = new StringTokenizer(header);

        //Different request parts
        String httpMethod = tokenizer.nextToken();
        String httpQueryString = tokenizer.nextToken();

        //Print client request
        StringBuffer responseBuffer = new StringBuffer();
        while (clientRequest.ready()) {
            responseBuffer.append(requestString + " ");
            System.out.println(requestString);

            requestString = clientRequest.readLine();
        }

        //Process GET request
        if (httpMethod.equals("GET")) {
            processGETRequests(httpQueryString, requestString);


        }else if (httpMethod.equals("POST")) {
            processPOSTRequests(responseBuffer, httpQueryString);
        }
    }

1 个答案:

答案 0 :(得分:1)

仔细阅读ready()的文档。

我认为你的问题是:

while (clientRequest.ready()) {

如果流还没有数据(如果客户端发送的速度比服务器处理的速度慢),那么您不会等待客户端发送它。