2
I am trying to consume a weather forecast API (https://openweathermap.org/current) in Java but I have a question regarding the return of JSONObject
.
I’m using the following code to generate the JSONObject
:
JSONObject obj = new JSONObject(IOUtils.toString(new URL(url), Charset.forName("UTF-8")));
And when I put a valid URL (https://api.openweathermap.org/data/2.5/weather?q=sao+paulo&appid=ccad5d6394c0ebed411edff3fccecb67&lang=pt&units=metric) it works, I can manipulate without problems.
But when I use an invalid URL (https://api.openweathermap.org/data/2.5/weather?q=ABCD&appid=ccad5d6394c0ebed411edff3fccecb67&lang=pt&units=metric) the API returns me a JSON with the 404 code information, but in the browser it accuses the following error:
There was an unexpected error (type=Internal Server Error, status=500).
And in the IDE the following error:
java.io.FileNotFoundException: http://api.openweathermap.org/data/2.5/weather?q=ABCD&appid=ccad5d6394c0ebed411edff3fccecb67&lang=pt&units=metric
at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1890) ~[na:1.8.0_191]
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1492) ~[na:1.8.0_191]
at java.net.URL.openStream(URL.java:1045) ~[na:1.8.0_191]
at org.apache.commons.io.IOUtils.toString(IOUtils.java:1153) ~[commons-io-2.5.jar:2.5]
The question is, instead of giving the status 500 (Internal Server Error) error, shouldn’t I return the JSON with the 404 error information? How can I get around this problem by getting error 404 of not found in order to deal with the code?
I may be completely wrong, but I believe that since the browser only "displays" what java sent the errors generated by the browser are other.
– Jonathan CR
It is actually a server created with Spring and Maven, so when I request it, it represents the server error in the browser, so I think doing the check with Conn.getResponseCode() I’ll be able to handle the requisition before I even execute the Conn.getInputStream()
– Marcos Couto