[Java] My HTTP request is using the URL's openStream() method to read and pull the contents of the URL. My servlet is able to access the URL successfully and is also successfully traversing through the content inside the while loop. However, the StringBuilder value/HTML response is returning null. All the debug logs for "content" are showing null.
Here is my code. Any help would be greatly appreciated.
Writer writer = response.getWriter();
try {
StringBuilder content = new StringBuilder("ContentEDL ");
LOG.info("EDLHost: Inside try block");
String str = "https://www.google.com";
URL url = new URL(str);
LOG.error("EDLStr: " + str);
LOG.error("EDLHost: " + url.getHost());
//HttpURLConnection con = (HttpURLConnection) url.openConnection();
//LOG.error("EDLCode: "+ con.getResponseCode());
//URLConnection con = url.openConnection();
LOG.error("EDLFile : " + url.getFile());
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
LOG.error("Inside EDLWhileLoop " + inputLine);
content.append(inputLine);
LOG.error("ContentAppended: " + content);
writer.append(content);
//System.out.println(inputLine);
LOG.error("EDLContent : " + content);
in.close();
//writer.append(content);
} catch (IOException e) {
LOG.error("EDLexception: {}", e);
e.printStackTrace();
}
I think there is problem with while loop bracket. Try with below code.
Writer writer = response.getWriter();
try {
StringBuilder content = new StringBuilder("ContentEDL ");
LOG.info("EDLHost: Inside try block");
String str = "https://www.google.com";
URL url = new URL(str);
LOG.error("EDLStr: " + str);
LOG.error("EDLHost: " + url.getHost());
//HttpURLConnection con = (HttpURLConnection) url.openConnection();
//LOG.error("EDLCode: "+ con.getResponseCode());
//URLConnection con = url.openConnection();
LOG.error("EDLFile : " + url.getFile());
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
LOG.error("Inside EDLWhileLoop " + inputLine);
content.append(inputLine);
}
LOG.error("ContentAppended: " + content);
writer.append(content);
//System.out.println(inputLine);
LOG.error("EDLContent : " + content);
in.close();
//writer.append(content);
} catch (IOException e) {
LOG.error("EDLexception: {}", e);
e.printStackTrace();
}