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.
Don't parse the string. Go back one step, and check the Content-Type
header of the HTTP response. If the response contains JSON data, the Content-Type
should be application/json
(source).
Check the MediaType in the response using response.getMediaType(). If it is json it returns application/json.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With