Skip to content

Commit f89fe94

Browse files
authored
fix(java): send request bodies with Content-Length instead of chunked encoding (#7069)
1 parent 63e1f25 commit f89fe94

2 files changed

Lines changed: 97 additions & 13 deletions

File tree

‎clients/algoliasearch-client-java/algoliasearch/src/main/java/com/algolia/internal/HttpRequester.java‎

Lines changed: 8 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
import com.algolia.utils.UseReadTransporter;
99
import com.fasterxml.jackson.core.type.TypeReference;
1010
import com.fasterxml.jackson.databind.JavaType;
11+
import java.io.ByteArrayOutputStream;
1112
import java.io.IOException;
1213
import java.time.Duration;
1314
import java.util.ArrayList;
@@ -17,7 +18,6 @@
1718
import javax.annotation.Nonnull;
1819
import okhttp3.*;
1920
import okhttp3.internal.http.HttpMethod;
20-
import okio.BufferedSink;
2121

2222
/**
2323
* HttpRequester is responsible for making HTTP requests using the OkHttp client. It provides a
@@ -134,20 +134,15 @@ private RequestBody createRequestBody(HttpRequest httpRequest) {
134134
return buildRequestBody(body);
135135
}
136136

137-
/** Serializes the request body into JSON format. */
137+
/**
138+
* Serializes the request body into JSON and returns a fixed-length request body so OkHttp sends
139+
* {@code Content-Length} instead of {@code Transfer-Encoding: chunked}.
140+
*/
138141
@Nonnull
139142
private RequestBody buildRequestBody(Object requestBody) {
140-
return new RequestBody() {
141-
@Override
142-
public MediaType contentType() {
143-
return JSON_MEDIA_TYPE;
144-
}
145-
146-
@Override
147-
public void writeTo(@Nonnull BufferedSink bufferedSink) {
148-
serializer.serialize(bufferedSink.outputStream(), requestBody);
149-
}
150-
};
143+
ByteArrayOutputStream stream = new ByteArrayOutputStream();
144+
serializer.serialize(stream, requestBody);
145+
return RequestBody.create(stream.toByteArray(), JSON_MEDIA_TYPE);
151146
}
152147

153148
/** Constructs the headers for the HTTP request. */
Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,89 @@
1+
package com.algolia.manual;
2+
3+
import static org.junit.jupiter.api.Assertions.*;
4+
5+
import com.algolia.api.SearchClient;
6+
import com.algolia.config.ClientOptions;
7+
import java.io.IOException;
8+
import java.nio.charset.StandardCharsets;
9+
import java.util.LinkedHashMap;
10+
import java.util.Map;
11+
import okhttp3.Interceptor;
12+
import okhttp3.MediaType;
13+
import okhttp3.Protocol;
14+
import okhttp3.RequestBody;
15+
import okhttp3.Response;
16+
import okhttp3.ResponseBody;
17+
import okio.Buffer;
18+
import org.junit.jupiter.api.DisplayName;
19+
import org.junit.jupiter.api.Test;
20+
import org.junit.jupiter.api.Timeout;
21+
22+
/**
23+
* Pins the wire contract from API-141 / CR-12179: request bodies are pre-serialized to UTF-8 bytes
24+
* and declare their exact length, so requests carry {@code Content-Length} instead of {@code
25+
* Transfer-Encoding: chunked}.
26+
*/
27+
class RequestBodyContentLengthTest {
28+
29+
static final class BodyCaptureInterceptor implements Interceptor {
30+
31+
Long contentLength;
32+
String bodyUtf8;
33+
34+
@Override
35+
public Response intercept(Chain chain) throws IOException {
36+
RequestBody body = chain.request().body();
37+
if (body != null) {
38+
contentLength = body.contentLength();
39+
Buffer buffer = new Buffer();
40+
body.writeTo(buffer);
41+
bodyUtf8 = buffer.readUtf8();
42+
}
43+
return new Response.Builder()
44+
.code(200)
45+
.request(chain.request())
46+
.protocol(Protocol.HTTP_2)
47+
.message("")
48+
.body(ResponseBody.create("{}", MediaType.parse("application/json")))
49+
.build();
50+
}
51+
}
52+
53+
private static SearchClient clientWith(Interceptor interceptor) {
54+
return new SearchClient(
55+
"appId",
56+
"apiKey",
57+
ClientOptions.builder().setRequesterConfig(requester -> requester.addInterceptor(interceptor)).build()
58+
);
59+
}
60+
61+
@Test
62+
@Timeout(10)
63+
@DisplayName("request bodies declare their exact UTF-8 byte length instead of chunked encoding")
64+
void requestBodiesDeclareExactUtf8Length() throws Exception {
65+
BodyCaptureInterceptor capture = new BodyCaptureInterceptor();
66+
Map<String, String> payload = new LinkedHashMap<String, String>();
67+
payload.put("message", "café");
68+
69+
try (SearchClient client = clientWith(capture)) {
70+
client.customPost("1/test", null, payload);
71+
String expected = "{\"message\":\"café\"}";
72+
assertEquals(expected, capture.bodyUtf8);
73+
assertEquals(Long.valueOf(expected.getBytes(StandardCharsets.UTF_8).length), capture.contentLength);
74+
}
75+
}
76+
77+
@Test
78+
@Timeout(10)
79+
@DisplayName("bodyless POST sends a fixed-length empty JSON object")
80+
void bodylessPostSendsFixedLengthEmptyObject() throws Exception {
81+
BodyCaptureInterceptor capture = new BodyCaptureInterceptor();
82+
83+
try (SearchClient client = clientWith(capture)) {
84+
client.customPost("1/test");
85+
assertEquals("{}", capture.bodyUtf8);
86+
assertEquals(Long.valueOf(2L), capture.contentLength);
87+
}
88+
}
89+
}

0 commit comments

Comments
 (0)