0

I have never worked with Java up until this point. I have to create a web application for a project in which I am using a RapidAPI web service to search for movies based on a search query. The code sets up the servlet and defines the doGet method, which is called when the servlet receives a GET request from a client. The method retrieves the search query from the request and uses the RapidAPI service to search for movies that match the query. The results are then returned to the client in an HTML response. The problem is I keep having this error that I don't know how to solve. This is the code:

HttpResponse<JsonNode> response;
try {
response = Unirest.get(host + "?" + query)
.header("x-rapidapi-host", x_rapidapi_host)
.header("x-rapidapi-key", x_rapidapi_key)
.asJson();
} catch (UnirestException e) {
        // TODO Auto-generated catch block
e.printStackTrace();
}

  //Prettifying
Gson gson = new GsonBuilder().setPrettyPrinting().create();
JsonParser jp = new JsonParser();
JsonElement je = jp.parse(response.getBody().toString());
String prettyJsonString = gson.toJson(je);  

resp.setContentType("text/html");
PrintWriter printWriter = resp.getWriter();
printWriter.print("<html>");
printWriter.print("<body>");
printWriter.print("<h1>Movie search engine</h1>");
printWriter.print("<p>Search result:" + prettyJsonString + "</p>");
printWriter.print("</body>");
printWriter.print("</html>");
printWriter.close();

This is the first time asking a question here so I hope I offered all the information needed.

I think the problem is in the try-catch part of the code and I tried adding an exception to the method but then I had another error: Unhandled exception type UnirestException. This was the only way to solve the exception.

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • You can't use `response` where you are trying to because the assignment to it may have failed. That statement needs to go in the `try` block, where you can be assured it has a value. – Scott Hunter Dec 13 '22 at 22:43
  • 1
    Side note: always post the full error message in your question in an easily readable way. It truly is the most important bit of information. – DontKnowMuchBut Getting Better Dec 13 '22 at 22:45

1 Answers1

0

If the code inside the try-catch throws an exception, the response variable will remain uninitialized. You can either initialize it by specifying its value along with the declaration (and then overwrite the value in the try section) or set its value in the catch block.

Anna Dolbina
  • 1
  • 1
  • 8
  • 9