or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

async-execution.mdauthentication-security.mdcaching.mdconnection-management.mdform-data-multipart.mdhttp-client.mdhttp-utilities.mdindex.mdinterceptors.mdrequest-building.mdrequest-response-bodies.mdresponse-handling.md

request-response-bodies.mddocs/

0

# Request and Response Bodies

1

2

Support for various content types with efficient streaming, multiple access patterns, and proper resource management.

3

4

## Capabilities

5

6

### RequestBody

7

8

Abstract base class for HTTP request bodies with content type and writing capability.

9

10

```java { .api }

11

/**

12

* Abstract base for HTTP request bodies.

13

*/

14

public abstract class RequestBody {

15

public static RequestBody create(MediaType contentType, String content);

16

public static RequestBody create(MediaType contentType, ByteString content);

17

public static RequestBody create(MediaType contentType, byte[] content);

18

public static RequestBody create(MediaType contentType, byte[] content, int offset, int byteCount);

19

public static RequestBody create(MediaType contentType, File file);

20

public abstract MediaType contentType();

21

public long contentLength() throws IOException;

22

public abstract void writeTo(BufferedSink sink) throws IOException;

23

}

24

```

25

26

**Usage Examples:**

27

28

```java

29

// String content

30

RequestBody body = RequestBody.create(

31

MediaType.parse("application/json"),

32

"{\"name\":\"John\",\"email\":\"john@example.com\"}"

33

);

34

35

// File content

36

File file = new File("data.json");

37

RequestBody body = RequestBody.create(MediaType.parse("application/json"), file);

38

39

// Byte array content

40

byte[] data = "Hello, World!".getBytes("UTF-8");

41

RequestBody body = RequestBody.create(MediaType.parse("text/plain"), data);

42

```

43

44

### ResponseBody

45

46

Abstract base class for HTTP response bodies providing multiple access methods.

47

48

```java { .api }

49

/**

50

* Abstract base for HTTP response bodies.

51

*/

52

public abstract class ResponseBody {

53

public static ResponseBody create(MediaType contentType, String content);

54

public static ResponseBody create(MediaType contentType, byte[] content);

55

public static ResponseBody create(MediaType contentType, long contentLength, BufferedSource content);

56

public abstract MediaType contentType();

57

public abstract long contentLength() throws IOException;

58

public abstract BufferedSource source() throws IOException;

59

public final String string() throws IOException;

60

public final byte[] bytes() throws IOException;

61

public final InputStream byteStream() throws IOException;

62

public final Reader charStream() throws IOException;

63

public void close() throws IOException;

64

}

65

```

66

67

**Usage Examples:**

68

69

```java

70

Response response = client.newCall(request).execute();

71

try {

72

ResponseBody body = response.body();

73

74

// Get content type and length

75

MediaType contentType = body.contentType();

76

long contentLength = body.contentLength(); // -1 if unknown

77

78

// Access as string (reads entire response into memory)

79

String content = body.string();

80

81

// Alternative: Access as bytes

82

// byte[] bytes = body.bytes();

83

84

// Alternative: Stream processing for large responses

85

// InputStream stream = body.byteStream();

86

// BufferedReader reader = new BufferedReader(new InputStreamReader(stream));

87

88

} finally {

89

response.body().close(); // Always close

90

}

91

```

92

93

### Creating Request Bodies

94

95

Various factory methods for creating request bodies from different sources.

96

97

```java { .api }

98

/**

99

* Creates a RequestBody from a string with the specified content type.

100

* @param contentType the media type

101

* @param content the string content

102

* @return RequestBody instance

103

*/

104

public static RequestBody create(MediaType contentType, String content);

105

106

/**

107

* Creates a RequestBody from a byte array with the specified content type.

108

* @param contentType the media type

109

* @param content the byte array content

110

* @return RequestBody instance

111

*/

112

public static RequestBody create(MediaType contentType, byte[] content);

113

114

/**

115

* Creates a RequestBody from a portion of a byte array.

116

* @param contentType the media type

117

* @param content the byte array

118

* @param offset the starting position

119

* @param byteCount the number of bytes to include

120

* @return RequestBody instance

121

*/

122

public static RequestBody create(MediaType contentType, byte[] content, int offset, int byteCount);

123

124

/**

125

* Creates a RequestBody from a file with the specified content type.

126

* @param contentType the media type

127

* @param file the file to read

128

* @return RequestBody instance

129

*/

130

public static RequestBody create(MediaType contentType, File file);

131

```

132

133

**Usage Examples:**

134

135

```java

136

// JSON request body

137

String json = "{\"username\":\"john\",\"password\":\"secret\"}";

138

RequestBody jsonBody = RequestBody.create(

139

MediaType.parse("application/json; charset=utf-8"),

140

json

141

);

142

143

// XML request body

144

String xml = "<?xml version=\"1.0\"?><user><name>John</name></user>";

145

RequestBody xmlBody = RequestBody.create(

146

MediaType.parse("application/xml"),

147

xml

148

);

149

150

// File upload

151

File imageFile = new File("photo.jpg");

152

RequestBody fileBody = RequestBody.create(

153

MediaType.parse("image/jpeg"),

154

imageFile

155

);

156

157

// Binary data

158

byte[] binaryData = loadBinaryData();

159

RequestBody binaryBody = RequestBody.create(

160

MediaType.parse("application/octet-stream"),

161

binaryData

162

);

163

164

// Partial byte array

165

byte[] data = "Hello, World! This is a longer message.".getBytes();

166

RequestBody partialBody = RequestBody.create(

167

MediaType.parse("text/plain"),

168

data,

169

7, // offset: start after "Hello, "

170

5 // length: "World"

171

);

172

```

173

174

### Content Properties

175

176

Access content type and length information.

177

178

```java { .api }

179

/**

180

* Returns the content type of this body, or null if unknown.

181

* @return the MediaType or null

182

*/

183

public abstract MediaType contentType();

184

185

/**

186

* Returns the content length of this body in bytes, or -1 if unknown.

187

* @return the content length or -1

188

*/

189

public long contentLength() throws IOException;

190

```

191

192

**Usage Examples:**

193

194

```java

195

// For RequestBody

196

RequestBody body = RequestBody.create(MediaType.parse("text/plain"), "Hello");

197

MediaType type = body.contentType(); // text/plain

198

long length = body.contentLength(); // 5

199

200

// For ResponseBody

201

Response response = client.newCall(request).execute();

202

ResponseBody responseBody = response.body();

203

MediaType responseType = responseBody.contentType();

204

long responseLength = responseBody.contentLength();

205

206

if (responseLength > 0) {

207

System.out.println("Response size: " + responseLength + " bytes");

208

} else {

209

System.out.println("Response size unknown (chunked transfer)");

210

}

211

```

212

213

### Streaming Request Bodies

214

215

Create custom request bodies with streaming capability.

216

217

```java { .api }

218

/**

219

* Writes the content of this request to sink.

220

* @param sink the sink to write to

221

* @throws IOException if writing fails

222

*/

223

public abstract void writeTo(BufferedSink sink) throws IOException;

224

```

225

226

**Custom RequestBody Example:**

227

228

```java

229

// Custom streaming request body

230

RequestBody customBody = new RequestBody() {

231

@Override

232

public MediaType contentType() {

233

return MediaType.parse("application/json");

234

}

235

236

@Override

237

public long contentLength() throws IOException {

238

return -1; // Unknown length (will use chunked encoding)

239

}

240

241

@Override

242

public void writeTo(BufferedSink sink) throws IOException {

243

// Stream data as it becomes available

244

for (int i = 0; i < 1000; i++) {

245

String json = "{\"id\":" + i + ",\"data\":\"item" + i + "\"}\n";

246

sink.writeUtf8(json);

247

sink.flush();

248

249

// Simulate data generation delay

250

try { Thread.sleep(10); } catch (InterruptedException e) {}

251

}

252

}

253

};

254

255

Request request = new Request.Builder()

256

.url("https://api.example.com/stream")

257

.post(customBody)

258

.build();

259

```

260

261

### Response Body Access Methods

262

263

Multiple ways to access response body content depending on use case.

264

265

```java { .api }

266

/**

267

* Returns the response as a string. This method loads entire response into memory.

268

* @return the response body as a string

269

* @throws IOException if reading fails

270

*/

271

public final String string() throws IOException;

272

273

/**

274

* Returns the response as a byte array. This method loads entire response into memory.

275

* @return the response body as bytes

276

* @throws IOException if reading fails

277

*/

278

public final byte[] bytes() throws IOException;

279

280

/**

281

* Returns an InputStream for reading the response body.

282

* @return InputStream for the response body

283

* @throws IOException if stream creation fails

284

*/

285

public final InputStream byteStream() throws IOException;

286

287

/**

288

* Returns a Reader for reading the response body as characters.

289

* @return Reader for the response body

290

* @throws IOException if reader creation fails

291

*/

292

public final Reader charStream() throws IOException;

293

294

/**

295

* Returns a BufferedSource for advanced reading operations.

296

* @return BufferedSource for the response body

297

* @throws IOException if source creation fails

298

*/

299

public abstract BufferedSource source() throws IOException;

300

```

301

302

**Usage Examples:**

303

304

```java

305

Response response = client.newCall(request).execute();

306

try {

307

ResponseBody body = response.body();

308

309

// For small responses: read as string

310

if (body.contentLength() < 1024 * 1024) { // < 1MB

311

String content = body.string();

312

System.out.println(content);

313

}

314

// For large responses: stream processing

315

else {

316

InputStream stream = body.byteStream();

317

BufferedReader reader = new BufferedReader(new InputStreamReader(stream));

318

String line;

319

while ((line = reader.readLine()) != null) {

320

processLine(line);

321

}

322

}

323

324

// For binary data

325

// byte[] data = body.bytes();

326

327

// For character processing with encoding detection

328

// Reader reader = body.charStream();

329

330

} finally {

331

response.body().close();

332

}

333

```

334

335

### Resource Management

336

337

Proper resource management for response bodies to prevent memory leaks.

338

339

```java { .api }

340

/**

341

* Closes the response body and releases associated resources.

342

* @throws IOException if closing fails

343

*/

344

public void close() throws IOException;

345

```

346

347

**Best Practices:**

348

349

```java

350

// Always use try-finally

351

Response response = client.newCall(request).execute();

352

try {

353

String content = response.body().string();

354

// Process content...

355

} finally {

356

response.body().close(); // Critical: prevents resource leaks

357

}

358

359

// Or use try-with-resources (Response implements Closeable)

360

try (Response response = client.newCall(request).execute()) {

361

String content = response.body().string();

362

// Process content...

363

} // Automatically closed

364

365

// For streaming, close the stream

366

Response response = client.newCall(request).execute();

367

try (InputStream stream = response.body().byteStream();

368

BufferedReader reader = new BufferedReader(new InputStreamReader(stream))) {

369

370

String line;

371

while ((line = reader.readLine()) != null) {

372

processLine(line);

373

}

374

} finally {

375

response.body().close();

376

}

377

```

378

379

### Empty and Simple Bodies

380

381

Handling empty bodies and simple content creation.

382

383

**Usage Examples:**

384

385

```java

386

// Empty request body for DELETE

387

RequestBody emptyBody = RequestBody.create(null, new byte[0]);

388

Request deleteRequest = new Request.Builder()

389

.url("https://api.example.com/resource/1")

390

.delete(emptyBody)

391

.build();

392

393

// Or use the convenience method

394

Request deleteRequest2 = new Request.Builder()

395

.url("https://api.example.com/resource/1")

396

.delete() // Automatically creates empty body

397

.build();

398

399

// Simple text body

400

RequestBody textBody = RequestBody.create(

401

MediaType.parse("text/plain"),

402

"Simple text content"

403

);

404

405

// Check for empty response

406

Response response = client.newCall(request).execute();

407

if (response.body().contentLength() == 0) {

408

System.out.println("Empty response body");

409

} else {

410

String content = response.body().string();

411

}

412

```