Java - Check Response - JSON or not.

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.

+4
source share
2 answers

Do not 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 must be application/json ( source ).

+7
source

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

+1
source

Source: https://habr.com/ru/post/1499202/


All Articles