Skip to content
This repository was archived by the owner on Jan 31, 2022. It is now read-only.

Commit a8c2690

Browse files
author
Clément Le Provost
committed
fix: Send large API keys in the body of the request
This avoids the server rejecting requests because of too large headers.
1 parent 30200c5 commit a8c2690

File tree

1 file changed

+15
-1
lines changed

1 file changed

+15
-1
lines changed

algoliasearch/src/main/java/com/algolia/search/saas/AbstractClient.java

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -107,6 +107,9 @@ private static class HostStatus {
107107
/** This library's version. */
108108
private final static String version = "3.12.0";
109109

110+
/** Maximum size for an API key to be sent in the HTTP headers. Bigger keys will go inside the body. */
111+
private final static int MAX_API_KEY_LENGTH = 500;
112+
110113
// ----------------------------------------------------------------------
111114
// Fields
112115
// ----------------------------------------------------------------------
@@ -545,7 +548,18 @@ private byte[] _requestRaw(Method m, String url, String json, List<String> hosts
545548

546549
// set auth headers
547550
hostConnection.setRequestProperty("X-Algolia-Application-Id", this.applicationID);
548-
hostConnection.setRequestProperty("X-Algolia-API-Key", this.apiKey);
551+
// If API key is too big, send it in the request's body (if applicable).
552+
if (this.apiKey != null && this.apiKey.length() > MAX_API_KEY_LENGTH && json != null) {
553+
try {
554+
final JSONObject body = new JSONObject(json);
555+
body.put("apiKey", this.apiKey);
556+
json = body.toString();
557+
} catch (JSONException e) {
558+
throw new AlgoliaException("Failed to patch JSON body");
559+
}
560+
} else {
561+
hostConnection.setRequestProperty("X-Algolia-API-Key", this.apiKey);
562+
}
549563
for (Map.Entry<String, String> entry : this.headers.entrySet()) {
550564
hostConnection.setRequestProperty(entry.getKey(), entry.getValue());
551565
}

0 commit comments

Comments
 (0)