An HTTP & SPDY client for Android and Java applications with efficient connection pooling, interceptors, and modern protocol support
—
Support for various content types with efficient streaming, multiple access patterns, and proper resource management.
Abstract base class for HTTP request bodies with content type and writing capability.
/**
* Abstract base for HTTP request bodies.
*/
public abstract class RequestBody {
public static RequestBody create(MediaType contentType, String content);
public static RequestBody create(MediaType contentType, ByteString content);
public static RequestBody create(MediaType contentType, byte[] content);
public static RequestBody create(MediaType contentType, byte[] content, int offset, int byteCount);
public static RequestBody create(MediaType contentType, File file);
public abstract MediaType contentType();
public long contentLength() throws IOException;
public abstract void writeTo(BufferedSink sink) throws IOException;
}Usage Examples:
// String content
RequestBody body = RequestBody.create(
MediaType.parse("application/json"),
"{\"name\":\"John\",\"email\":\"john@example.com\"}"
);
// File content
File file = new File("data.json");
RequestBody body = RequestBody.create(MediaType.parse("application/json"), file);
// Byte array content
byte[] data = "Hello, World!".getBytes("UTF-8");
RequestBody body = RequestBody.create(MediaType.parse("text/plain"), data);Abstract base class for HTTP response bodies providing multiple access methods.
/**
* Abstract base for HTTP response bodies.
*/
public abstract class ResponseBody {
public static ResponseBody create(MediaType contentType, String content);
public static ResponseBody create(MediaType contentType, byte[] content);
public static ResponseBody create(MediaType contentType, long contentLength, BufferedSource content);
public abstract MediaType contentType();
public abstract long contentLength() throws IOException;
public abstract BufferedSource source() throws IOException;
public final String string() throws IOException;
public final byte[] bytes() throws IOException;
public final InputStream byteStream() throws IOException;
public final Reader charStream() throws IOException;
public void close() throws IOException;
}Usage Examples:
Response response = client.newCall(request).execute();
try {
ResponseBody body = response.body();
// Get content type and length
MediaType contentType = body.contentType();
long contentLength = body.contentLength(); // -1 if unknown
// Access as string (reads entire response into memory)
String content = body.string();
// Alternative: Access as bytes
// byte[] bytes = body.bytes();
// Alternative: Stream processing for large responses
// InputStream stream = body.byteStream();
// BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
} finally {
response.body().close(); // Always close
}Various factory methods for creating request bodies from different sources.
/**
* Creates a RequestBody from a string with the specified content type.
* @param contentType the media type
* @param content the string content
* @return RequestBody instance
*/
public static RequestBody create(MediaType contentType, String content);
/**
* Creates a RequestBody from a byte array with the specified content type.
* @param contentType the media type
* @param content the byte array content
* @return RequestBody instance
*/
public static RequestBody create(MediaType contentType, byte[] content);
/**
* Creates a RequestBody from a portion of a byte array.
* @param contentType the media type
* @param content the byte array
* @param offset the starting position
* @param byteCount the number of bytes to include
* @return RequestBody instance
*/
public static RequestBody create(MediaType contentType, byte[] content, int offset, int byteCount);
/**
* Creates a RequestBody from a file with the specified content type.
* @param contentType the media type
* @param file the file to read
* @return RequestBody instance
*/
public static RequestBody create(MediaType contentType, File file);Usage Examples:
// JSON request body
String json = "{\"username\":\"john\",\"password\":\"secret\"}";
RequestBody jsonBody = RequestBody.create(
MediaType.parse("application/json; charset=utf-8"),
json
);
// XML request body
String xml = "<?xml version=\"1.0\"?><user><name>John</name></user>";
RequestBody xmlBody = RequestBody.create(
MediaType.parse("application/xml"),
xml
);
// File upload
File imageFile = new File("photo.jpg");
RequestBody fileBody = RequestBody.create(
MediaType.parse("image/jpeg"),
imageFile
);
// Binary data
byte[] binaryData = loadBinaryData();
RequestBody binaryBody = RequestBody.create(
MediaType.parse("application/octet-stream"),
binaryData
);
// Partial byte array
byte[] data = "Hello, World! This is a longer message.".getBytes();
RequestBody partialBody = RequestBody.create(
MediaType.parse("text/plain"),
data,
7, // offset: start after "Hello, "
5 // length: "World"
);Access content type and length information.
/**
* Returns the content type of this body, or null if unknown.
* @return the MediaType or null
*/
public abstract MediaType contentType();
/**
* Returns the content length of this body in bytes, or -1 if unknown.
* @return the content length or -1
*/
public long contentLength() throws IOException;Usage Examples:
// For RequestBody
RequestBody body = RequestBody.create(MediaType.parse("text/plain"), "Hello");
MediaType type = body.contentType(); // text/plain
long length = body.contentLength(); // 5
// For ResponseBody
Response response = client.newCall(request).execute();
ResponseBody responseBody = response.body();
MediaType responseType = responseBody.contentType();
long responseLength = responseBody.contentLength();
if (responseLength > 0) {
System.out.println("Response size: " + responseLength + " bytes");
} else {
System.out.println("Response size unknown (chunked transfer)");
}Create custom request bodies with streaming capability.
/**
* Writes the content of this request to sink.
* @param sink the sink to write to
* @throws IOException if writing fails
*/
public abstract void writeTo(BufferedSink sink) throws IOException;Custom RequestBody Example:
// Custom streaming request body
RequestBody customBody = new RequestBody() {
@Override
public MediaType contentType() {
return MediaType.parse("application/json");
}
@Override
public long contentLength() throws IOException {
return -1; // Unknown length (will use chunked encoding)
}
@Override
public void writeTo(BufferedSink sink) throws IOException {
// Stream data as it becomes available
for (int i = 0; i < 1000; i++) {
String json = "{\"id\":" + i + ",\"data\":\"item" + i + "\"}\n";
sink.writeUtf8(json);
sink.flush();
// Simulate data generation delay
try { Thread.sleep(10); } catch (InterruptedException e) {}
}
}
};
Request request = new Request.Builder()
.url("https://api.example.com/stream")
.post(customBody)
.build();Multiple ways to access response body content depending on use case.
/**
* Returns the response as a string. This method loads entire response into memory.
* @return the response body as a string
* @throws IOException if reading fails
*/
public final String string() throws IOException;
/**
* Returns the response as a byte array. This method loads entire response into memory.
* @return the response body as bytes
* @throws IOException if reading fails
*/
public final byte[] bytes() throws IOException;
/**
* Returns an InputStream for reading the response body.
* @return InputStream for the response body
* @throws IOException if stream creation fails
*/
public final InputStream byteStream() throws IOException;
/**
* Returns a Reader for reading the response body as characters.
* @return Reader for the response body
* @throws IOException if reader creation fails
*/
public final Reader charStream() throws IOException;
/**
* Returns a BufferedSource for advanced reading operations.
* @return BufferedSource for the response body
* @throws IOException if source creation fails
*/
public abstract BufferedSource source() throws IOException;Usage Examples:
Response response = client.newCall(request).execute();
try {
ResponseBody body = response.body();
// For small responses: read as string
if (body.contentLength() < 1024 * 1024) { // < 1MB
String content = body.string();
System.out.println(content);
}
// For large responses: stream processing
else {
InputStream stream = body.byteStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
String line;
while ((line = reader.readLine()) != null) {
processLine(line);
}
}
// For binary data
// byte[] data = body.bytes();
// For character processing with encoding detection
// Reader reader = body.charStream();
} finally {
response.body().close();
}Proper resource management for response bodies to prevent memory leaks.
/**
* Closes the response body and releases associated resources.
* @throws IOException if closing fails
*/
public void close() throws IOException;Best Practices:
// Always use try-finally
Response response = client.newCall(request).execute();
try {
String content = response.body().string();
// Process content...
} finally {
response.body().close(); // Critical: prevents resource leaks
}
// Or use try-with-resources (Response implements Closeable)
try (Response response = client.newCall(request).execute()) {
String content = response.body().string();
// Process content...
} // Automatically closed
// For streaming, close the stream
Response response = client.newCall(request).execute();
try (InputStream stream = response.body().byteStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(stream))) {
String line;
while ((line = reader.readLine()) != null) {
processLine(line);
}
} finally {
response.body().close();
}Handling empty bodies and simple content creation.
Usage Examples:
// Empty request body for DELETE
RequestBody emptyBody = RequestBody.create(null, new byte[0]);
Request deleteRequest = new Request.Builder()
.url("https://api.example.com/resource/1")
.delete(emptyBody)
.build();
// Or use the convenience method
Request deleteRequest2 = new Request.Builder()
.url("https://api.example.com/resource/1")
.delete() // Automatically creates empty body
.build();
// Simple text body
RequestBody textBody = RequestBody.create(
MediaType.parse("text/plain"),
"Simple text content"
);
// Check for empty response
Response response = client.newCall(request).execute();
if (response.body().contentLength() == 0) {
System.out.println("Empty response body");
} else {
String content = response.body().string();
}Install with Tessl CLI
npx tessl i tessl/maven-com-squareup-okhttp--okhttp