CodeNameGrant
CodeNameGrant

Reputation: 136

Java PrintWriter not flushing full String

Im using AJAX to retrieve a JSONP response of an external system, however the response is being (for the lack of a better work) truncated. My front-end page will make the AJAX call to the URL, my system will generate a response which is added to a PrintWriter and then flush the Printwriter. However the content returned is not complete.

PrintWriter pw = response.getWriter();
pw.write(callBackFn);
pw.write("(" + requestsJSON + ")"); 
pw.flush();
pw.close();

Please note that the response is approx 120 000 characters. Ive tried looking for a reason for the cut-off but have found nothing like it.

EDIT

public ActionForward getJSON(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
        List requestList = RequestUtil.convertRequestsHashMapToRequestsList((HashMap)request.getSession().getServletContext().getAttribute(Constants.REQUESTS_CACHE_MAP));
        String requestsJSON = "";

        if (!requestList.isEmpty()) {
            Requests requestObj = (Requests) requestList.get(0);
            requestsJSON += "{\"key\":\"" + requestObj.getRequestId() + "\",\"value\":\"" + requestObj.getSubject() + "\"}";

            for (int i = 1; i < requestList.size(); i++) {
                requestObj = (Requests) requestList.get(i);
                requestsJSON += ",{\"key\":\"" + requestObj.getRequestId() + "\",\"value\":\"" + requestObj.getSubject() + "\"}";
            }
        }

        requestsJSON = "{\"values\":["+requestsJSON+"]}";
        String callBackFn = (String) request.getParameter("callback");

        System.out.println("#### Character length: " + (callBackFn + "(" + requestsJSON + ")").length());

        PrintWriter pw = response.getWriter();
        pw.write(callBackFn);
        pw.write("(" + requestsJSON + ")"); 
        pw.flush();
        pw.close();

        return null;
    }

NOTE: The system that I've added the above method to is quite old and not maintained. it was created using AppFuse 1.8.2 (which uses Spring 2) and is running Java 1.4. Unfortunately the system wasn't written very well so updating to a later version of Java is not an option.

With regards to how the returned content (JSONP String) that the method returns is used, its irrelevant. an external system is calling a URL which links to this method which returns the string.

Upvotes: 1

Views: 709

Answers (1)

Junyang HE
Junyang HE

Reputation: 56

I had a similar issue with the PrintWriter:

response.getWriter().write(responseString);

After I change it to OutputStream:

response.getOutputStream().write(responseString.getBytes("UTF-8"));
response.flushBuffer();

It works. But I don't know why the PrintWriter does not work.

Upvotes: 1

Related Questions