I am creating a HealthCheck server page. Most servers return a JSONObject, and I can easily parse it using:
String jsonText = readAll(br); JSONObject json = new JSONObject(jsonText); JSONObject resp = json.getJSONObject("Response");
Now my problem is other servers that do not return JSON. Some of them return String, some pdf files have some image, and since all answers are 200 OK, I have to return Positive healthcheck.
However, I use Future Threads and cross out my request after 4 seconds. And all the servers that return nothing but JSON get stuck in the "new JSONObject (jsonText)"
Is there any way to check if respone type is JSON or not in Java?
Update:
I found my mistake - dumb. In the try catch block, I only catch an IOException that does not catch a JSONException (and did not detect any error either - dunno y). I added a new catch block for JSONException, which works for my solution at the moment.
However, this is not an elegant solution; solutions by @Dave, @Radai and @Koi are the right approach.
source share