Arduino Mega web server always returning JSON data even if JSON is not passed in URL I am trying to return JSON data if JSON is found in the HTTP header, and if not I am trying to display a normal page. But instead it always displays the JSON text, even if I do not pass the JSON in the URL! Full code is here.

if (client) {
  // an http request ends with a blank line
  boolean currentLineIsBlank = true;
  boolean sentHeader = false;
  while (client.connected()) {
    if (client.available()) {
      // client data available to read
      char c = client.read(); // read 1 byte (character) from client
      // buffer first part of HTTP request in HTTP_req array (string)
      // leave last element in array as 0 to null terminate string (REQ_BUF_SZ - 1)
      if (req_index &lt; (REQ_BUF_SZ - 1)) {
        HTTP_req[req_index] = c; // save HTTP request character
        req_index++;
      }
      // last line of client request is blank and ends with \n
      // respond to client only after last line received
      if (c == '\n' &amp;&amp; currentLineIsBlank) {
        if (!sentHeader) {
          // send a standard http response header
          client.println(F("HTTP/1.1 200 OK"));
        }
        // Ajax request - send JSON output
        if (util::StrContains(HTTP_req, "json")) {
          // Spit out JSON data
          client.println("Content-Type: application/json;charset=utf-8");
          client.println("Server: ArduinoMega");
          client.println("Connnection: close");
          client.println();
          client.print("{\"arduino\":[{\"location\":\"outdoor\",\"celsius\":\"");
          client.print(tempInC);
          client.print("\"}]}");
          client.println();
          break;
        } else {
          client.println(F("Content-Type: text/html"));
          client.println(F("Connection: close")); // the connection will be closed after completion of the response
          client.println(F("Refresh: 1000")); // refresh the page automatically every 60 sec
          client.println();
          sentHeader = true;
          client.println(F("&lt;!DOCTYPE HTML&gt;"));
          client.println(F("&lt;html&gt;&lt;head&gt;&lt;title&gt;"));
          client.println(F("Welcome to Arduino WebServer&lt;/title&gt;"));
          util::printProgStr(client, htmlStyleMultiline );
          client.println(F("&lt;/head&gt;&lt;body style='background-color:grey'&gt;"));
          client.println(c);
          client.print(F("&lt;p style='color:red';style='font-family: Arial'&gt; LIVE: &lt;/p&gt;"));


Please help.
So figured out the problem, the issue was  I was closing the connection instead when it was json fetched, I had to keep alive the connection.

so replaced client.println("Connnection: close"); with  client.println("Connection: keep-alive");

which fixed the problem.