4

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.

Rahul Dabas
  • 686
  • 1
  • 12
  • 27
  • 3
    Try to parse it as JSON. If it doesn't parse, it's not JSON. Check the response's content type. If it's a file check the extension. Etc. – Dave Newton Aug 27 '13 at 17:51
  • 1
    why are they stuck? i'd expect some exception to be thrown .. are you reading the whole response into a string or runing the json parser right off the input stream ? – radai Aug 27 '13 at 17:51
  • Dave I am already trying to parse it as JSON. I am taking the response in a string "jsonText" and then putting this text in JSONObject. I get stuck at second step. – Rahul Dabas Aug 27 '13 at 17:52
  • @radai I am 1. grabbing the response in string and 2. creating JSONObject with this jsonText I am getting stuck at 2nd step. No exception is being thrown, except my thread timeout. – Rahul Dabas Aug 27 '13 at 17:54
  • 3
    You should also check the Content-Type header of the response; JSON content should be sent as `application/json` – alexkonradi Aug 27 '13 at 17:56

2 Answers2

7

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).

Community
  • 1
  • 1
kol
  • 24,444
  • 11
  • 70
  • 104
  • i don't believe this is a guarantee is it? – Woot4Moo Aug 27 '13 at 18:02
  • 1
    @woot4Moo its possible that JSOn response might have incorrect content-type but this is the official accepted format. Hence correct answer. However you can check to make sure by putting try catch block - thats what I am doing. – Rahul Dabas Aug 27 '13 at 18:07
1

Check the MediaType in the response using response.getMediaType(). If it is json it returns application/json.