title: How to get and process an XML Response after making an HTTP Request
body: <p>I have an iterative method that will make 100's of calls to a url and then parse the XML response and persist the data after each call. </p>
  
  <p>To accomplish this I have been trying to just use HttpURLConnection to get the response, convert it into a string, and then a document so I can process it and parse the tags/info I want using SAX. </p>
  
  <p>However, this method only works sometimes, intermediately I get the following exception: </p>
  
  <p><code>org.xml.sax.SAXParseException: Content is not allowed in prolog.</code></p>
  
  <p>The issue appears to be that the XML String doesn't always come back properly. Instead of getting the normal XML tag with the data in between like:</p>
  
  <p><code>&lt;?xml version="1.0" encoding="UTF-8" standalone="yes"?&gt; &lt;/xml&gt;</code></p>
  
  <p>I get something like this: </p>
  
  <p><code>{"created":"2019-03-18T13:19:41.484Z","count":3654,"offset":500 ....</code></p>
  
  <p>The string contains the data that I need, but for some reason it seems like the response doesn't always return it in the form I need. I have confirmed that this is an intermittent issue, meaning I have hit the same exact request and sometimes received the desired response and at others received the undesired response. </p>
  
  <p><strong>Method that makes the request</strong></p>
  
  <pre><code>URL url = new URL("Some URL");
  
  HttpURLConnection connection = (HttpURLConnection) url.openConnection();
  connection.setRequestMethod("GET");
  connection.setReadTimeout(5000);
  connection.setConnectTimeout(5000);
  
  int responseCode = connection.getResponseCode();
  
  if (responseCode != 200) {
      log.error("Received an invalid response: " + responseCode);
      return;
  }
  
  parseXml(convertResponseToXmlString(connection));
  
  connection.disconnect();
  </code></pre>
  
  <p><strong>Method that converts the response into a String</strong></p>
  
  <pre><code>private String convertResponseToXmlString(final HttpURLConnection connection) throws IOException
  {
      String inputLine;
  
      BufferedReader input = new BufferedReader(new InputStreamReader(connection.getInputStream()));
  
      StringBuffer content = new StringBuffer();
  
      while ((inputLine = input.readLine()) != null)
      {
          content.append(inputLine);
      }
  
      input.close();
  
      return content.toString().trim();
  }
  </code></pre>