I have stumbled upon to error mentioned in the title of this question, while testing my application. The code has worked perfectly fine yesterday, despite not making any changes to the code, this error started to appear, reapeating itself in the process. I checked if the model structure for the json string is correct, so json can parse the string into an object of class Root. After debugging I realized that the "root" object is null. The Json response and api call both worked perfectly fine, I checked the json string in the database, but the root object is still null.
What is the cause of this problem?
Call of the function which is supposed to return a root object in the controller:
@Controller
public class MenuController {
String ipAddress = new IpFetcher().fetchIpAddress();
BusinessDAO bDao = new BusinessDAO();
WeatherDAO wDao = new WeatherDAO();
GeoDAO geoDAO = new GeoDAO();
@GetMapping("/main")
public String redirectToMain(Model model) {
Root rootGeo = geoDAO.getLocationByIp(ipAddress);
ch.bbw.eb.apimashup.model.weather.Root rootWeather = wDao.getWeatherGeo(rootGeo.getGeo().getLongitude(), rootGeo.getGeo().getLatitude());
GeoDAO class which handles the api call:
public class GeoDAO {
RequestRepository reqRepo = new RequestRepository();
// SEARCH BY LOCATION AND TERM
public Root getLocationByIp(String ipAddress) {
Root root = null;
ApiRequest apiRequest = null;
try {
StringBuilder searchUrl = new StringBuilder("https://api.ipgeolocationapi.com/geolocate/" + ipAddress);
HttpURLConnection connection = (HttpURLConnection) new URL(searchUrl.toString()).openConnection();
connection.setRequestMethod("GET");
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
apiRequest = new ApiRequest(searchUrl.toString());
apiRequest.setApiResponse(new ApiResponse(readAll(reader)));
reqRepo.createRequest(apiRequest);
Gson gson = new Gson();
root = gson.fromJson(reader, Root.class);
} else {
System.out.println("Bad Request");
}
} catch(Exception e) {
e.printStackTrace();
}
return root;
}
private String readAll(Reader rd) throws IOException {
StringBuilder sb = new StringBuilder();
int cp;
while ((cp = rd.read()) != -1) {
sb.append((char) cp);
}
return sb.toString();
}
}
question from:
https://stackoverflow.com/questions/65943810/servlet-dispatcherservlet-in-context-with-path-threw-exception-request-pro 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…