Java – httpclient: determines the empty entity in the response

I want to know how to determine an empty HTTP response

For example, I perform HTTP post on the web server, but the web server will only return the status code of my HTTP post, and will not return any other content

The problem is that I wrote a small HTTP framework on Apache httpclient for automatic JSON parsing and so on So the default use case of this framework is to make a request and parse the response However, if the response does not contain data, as described in the above example, I will ensure that my framework skips JSON parsing

So I do this:

HttpResponse response = httpClient.execute(uriRequest);
httpentity entity = response.getEntity();
if (entity != null){
    InputStream in = entity.getContent();
    // json parsing
}

But entities are always= null. And the retrieved input stream is= null. Is there a simple way to determine whether the HTTP body is empty?

The only way I see is that the server response contains a content length header field set to 0 But not every server sets this field

Any suggestions?

Solution

In httpclient, getentity () can return null See the latest samples

However, there are differences between empty entities and entities It sounds like you have an empty entity (sorry, it's pedantic – just HTTP is pedantic.:) about detecting empty entities, have you tried to read from the entity input stream? If the response is an empty entity, the EOF should be obtained immediately

Do you need to determine whether the entity is empty without reading any bytes from the entity body? According to the above code, I don't think you do this If this is the case, you can wrap the entity InputStream with pushbackinputstream and check:

HttpResponse response = httpClient.execute(uriRequest);
httpentity entity = response.getEntity();
if(entity != null) {
    InputStream in = new PushbackInputStream(entity.getContent());
    try {
        int firstByte=in.read();
        if(firstByte != -1) {
            in.unread(firstByte);
            // json parsing
        }
        else {
            // empty
        }
    }
    finally {
        // Don't close so we can reuse the connection
        EntityUtils.consumeQuietly(entity);
        // Or,if you're sure you won't re-use the connection
        in.close();
    }
}

It's best not to read the entire response into memory in case it gets larger This solution will test for blankness using constant memory (4 bytes:)

Edit: < pedantry > in HTTP, if the request does not have a content length header, there should be a transfer encoding: chunked header If there is no @ r_ 258_ 301 @: chunked header, then you should have no entity instead of empty entity.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>