I am creating a Server HealthCheck page. Most of the servers return JSONObject and I am able to easily parse it using:
String jsonText = readAll(br);
JSONObject json = new JSONObject(jsonText);
JSONObject resp = json.getJSONObject("Response");
Now my problem is the other servers that do not return JSON. Some are returning String, some pdf file some image and as all the responses are 200 OK I should return Positive healthcheck.
However I am using Future Threads and timing out my request after 4 secs. And all the servers which return anything other than JSON get stuck at " new JSONObject(jsonText);"
Is there any way I can check if the type of respone is JSON or not in Java?
Update:
I found my mistake - stupid one. In the try catch block I am only catching IOException, which is not catching JSONException(and didnt show any error too - dunno y). I have added a new catch block for JSONException which works for my solution for now.
However, this isnt elegant solution, @Dave, @Radai and @Koi 's solutions is the right approach to go with.