001/* 002 * Licensed to the Apache Software Foundation (ASF) under one or more 003 * contributor license agreements. See the NOTICE file distributed with 004 * this work for additional information regarding copyright ownership. 005 * The ASF licenses this file to You under the Apache License, Version 2.0 006 * (the "License"); you may not use this file except in compliance with 007 * the License. You may obtain a copy of the License at 008 * 009 * http://www.apache.org/licenses/LICENSE-2.0 010 * 011 * Unless required by applicable law or agreed to in writing, software 012 * distributed under the License is distributed on an "AS IS" BASIS, 013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 014 * See the License for the specific language governing permissions and 015 * limitations under the License. 016 */ 017package org.apache.juneau.http; 018 019import java.io.*; 020 021/** 022 * An HTTP message body (entity), providing content and its associated metadata. 023 * 024 * <p> 025 * Implementations <b>should</b> stream content directly through {@link #writeTo(OutputStream)} rather than 026 * buffering the entire body in memory. Implementations that can determine the content length without buffering 027 * may return a non-negative value from {@link #getContentLength()}, which allows transports to set 028 * {@code Content-Length} headers efficiently. 029 * 030 * <h5 class='section'>See Also:</h5><ul> 031 * <li class='link'><a class="doclink" href="https://juneau.apache.org/docs/topics/NextGenRestClient">Next-Generation REST Client</a> 032 * </ul> 033 * 034 * @since 9.2.1 035 */ 036public interface HttpBody { 037 038 /** 039 * Returns the MIME content type of this body, e.g. {@code "application/json; charset=UTF-8"}. 040 * 041 * @return The content type, or <jk>null</jk> if unknown. 042 */ 043 String getContentType(); 044 045 /** 046 * Returns the content length in bytes, or {@code -1} if unknown. 047 * 048 * <p> 049 * Implementations that buffer content may return the exact length; streaming implementations should 050 * return {@code -1} to cause the transport to use chunked transfer encoding. 051 * 052 * @return The content length, or {@code -1} if unknown. 053 */ 054 default long getContentLength() { 055 return -1; 056 } 057 058 /** 059 * Writes the body content to the given output stream. 060 * 061 * <p> 062 * Implementations <b>must not</b> close {@code out}. 063 * 064 * @param out The stream to write to. Never <jk>null</jk>. 065 * @throws IOException If an I/O error occurs. 066 */ 067 void writeTo(OutputStream out) throws IOException; 068 069 /** 070 * Returns {@code true} if this body can be written more than once. 071 * 072 * <p> 073 * Streaming bodies backed by a one-shot {@link InputStream} should return {@code false}. 074 * Buffered bodies (byte arrays, strings, files) should return {@code true}. 075 * 076 * @return {@code true} if repeatable. 077 */ 078 default boolean isRepeatable() { 079 return false; 080 } 081}