Explain casting of ByteArrayRequestEntity as HttpEntity

724 Views Asked by At

I need to set a ByteArrayRequestEntity as the entity on an HttpPost object via the setEntity(...) method which expects an HttpEntity as a parameter. Via the Netbeans tip, I'm casting the ByteArrayRequestEntity as an HttpEntity, but I'm not sure exactly why that is allowable. HttpEntity is an interface, and I am not sure that the ByteArrayRequestEntity implements all the methods of that interface (or if it needs to). Can anyone please clarify that this is an allowable casting?

2

There are 2 best solutions below

1
On

You can't cast a ByteArrayRequestEntity to an HttpEntity, but you should be able to create one from it:

new ByteArrayRequestEntity(yourEntity.getContent())

The real problem is that you're mixing libraries. ByteArrayRequestEntity is from the outdated HttpClient 3.x library, and HttpEntity is from the new HttpComponents library, so they aren't directly compatible. If possible, you should switch everything over to HttpComponents.

2
On

It doesn't hurt to do some investigation, right?

According to Apache HTTP Components documentation, ByteArrayRequestEntity implements the interface RequestEntity, and not HttpEntity