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.

4

2 回答 2

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

于 2013-08-27T17:59:29.283 回答
1

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

于 2015-02-07T04:23:07.190 回答