Pregunta

I'm building a Java server and everything has been working as expected until now. I can serve up a static html page using two methods I wrote: body and header. Now, I am trying to write a new method called "bodywithQueryString".

Problem: It almost works, but after the page is loaded, the loading won't stop. It just loads and loads. This is not happening with my static pages.

The only difference between the old method and new bodyWithQueryString() method is that in the new method I am using a buffered reader and print writer. These are new-ish functions for me so I'm guessing I'm not doing it right.

Here's how my new method is supposed to function: I want to pass my route and querystring (queryarray) to bodyWithQueryString method. I want the method to read the file (from the route) to a byte output stream, do a replaceall on the key/value pair of the querystring while reading and, lastly, return the bytes. The getResponse() main method would then send the html to the browser.

Here's my code:

public void getResponse() throws Exception {
  String[] routeParts = parseRoute(route); //break apart route and querystring
  File theFile = new File(routeParts[0]);
  if (theFile.canRead()) {
    out.write(header( twoHundredStatusCode, routeParts[0], contentType(routeParts[0]) ) );

    if (routeParts.length > 1) {  //there must be a querystring
      String[] queryStringArray = parseQueryString(routeParts[1]); //break apart querystring
      out.write(bodyWithQueryString(routeParts[0], queryStringArray)); //use new body method
    }
    else out.write(body(routeParts[0])); //use original body method

    out.flush();

private byte[] bodyWithQueryString(String route, String[] queryArray)
    throws Exception {

      BufferedReader reader = new BufferedReader(new FileReader(route));
      ByteArrayOutputStream fileOut = new ByteArrayOutputStream();
      PrintWriter writer = new PrintWriter(fileOut);
      String line;

      while ((line = reader.readLine()) != null) writer.println(line.replaceAll(queryArray[0]    ,queryArray[1]));    

      writer.flush();
      writer.close();
      reader.close();
      return fileOut.toByteArray();
  }
¿Fue útil?

Solución

It seems to me that you are not returning Content-Length header. This makes it hard for browser know when to stop loading the response.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top