Skip to main content

HTTP Entities and Resources

The org.apache.juneau.http.entity package contains implementations of org.apache.http.HttpEntity. These are entities that can be sent or received with an HTTP message. They consist of a message body and the headers Content-Type, Content-Length, and Content-Encoding.

The org.apache.juneau.http.resource package contains implementations of HttpResource which are extensions of org.apache.http.HttpEntity with arbitrary headers added beyond the standard content headers.

HttpEntityBasicHttpEntityByteArrayEntity FileEntity StreamEntity ReaderEntity SerializedEntity StringEntityHttpResourceBasicResourceByteArrayResource FileResource StreamResource ReaderResource StringResource
Example
import static org.apache.juneau.http.HttpEntities.*;

byte[] payload = {...};

// Create via type builder.
HttpEntity entity = ByteArrayEntity
.create()
.content(payload)
.contentType(ContentType.APPLICATION_OCTET_STREAM);

// Create via HttpEntities.
HttpEntity entity = byteArrayEntity(payload, ContentType.APPLICATION_OCTET_STREAM);

HTTP entities and resources can be used by both the server and client side APIs described in later sections.

Server-side example:

// REST endpoint that simply echos an HTTP entity.
@RestPost(path="/entity")
public HttpEntity echoMyEntity(HttpEntity entity) {
return entity;
}

// REST endpoint that serves up a static file.
@RestGet(path="/resource/{fileName}")
public HttpResource getStaticFile(@Path String fileName, Locale locale) {
getContext().getStaticFiles().resolve(fileName, locale).orElseThrow(NotFound::new);
}

Client-side example:

// REST client that uses the echo REST endpoint above.

HttpEntity entity = byteArrayEntity(...);

entity = RestClient.create()
.build()
.rootUrl(URI)
.post("/entity", entity)
.run()
.assertStatus().asCode().is(200)
.getContent().as(ByteArrayEntity.class);