简体   繁体   中英

How to check if JSON respone returns [ ] or response with body using Java?

I have an API that hits multiple times for different Event IDs.
Few have date and few does not. I get this error:

Premature end of chunk coded message body: closing chunk expected

Here is my code :

CloseableHttpClient client = HttpClients.createDefault();
HttpGet request = new HttpGet("my API URL");

System.out.println("request:"+request.getURI());
String list = request.getURI().toString();

request.addHeader("Authorization",bearerToken); // Adding the bearer token
request.addHeader("Content-Type", "application/json");

CloseableHttpResponse response = client.execute(request);

//try
//{
    System.out.println(response.getStatusLine());
    System.out.println(response.getEntity().getContentLength());

    HttpEntity ent = response.getEntity();

    if(ent!=null)
    {
        //InputStream in = new PushbackInputStream(ent.getContent());
        //in = new ByteArrayInputStream(EntityUtils.toByteArray(ent));
        EntityUtils.consume(ent);
        System.out.println(response.getEntity());
        //in.close();
    }

Can someone tell me where I am going wrong or how are we suppose to do this?

If my response does not have data, I need to just print them and go to next Event ID and check.
Some of my API returns just [ ]. Very new to Java as well.

When you use json libraries, they usually have some methods to check weather the json object is empty or not. you can use them in your code, for example in JSONObject we have isEmpty() method which returns a boolean and it is what you need.

besides if your problem is just one of the conditional of the answers just put it in your "if condition" after checking not to being null, for example:

if (string != null || !string.equals("[]")) {
    // your code 
}

but this is not a general way and in this way your code is not compatible with all kinds of the answers.

Have you tried checking if the json object length is zero?

eg.

if(ent.length == 0){
    //Do thing
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM