square/okhttp · error · IOException
Unexpected code
Error message
Unexpected code
What it means
UploadProgress.java:75 throws 'Unexpected code ' when the POST to https://api.imgur.com/3/image returns non-2xx. The recipe authenticates with a hardcoded Client-ID '9199fdef135c122' (line 32) via the Authorization header, and POSTs docs/images/logo-square.png wrapped in a ProgressRequestBody that counts bytes via a ForwardingSink. The isSuccessful() guard runs after the body has been fully transmitted, so progress completes before the error is raised.
Source
Thrown at samples/guide/src/main/java/okhttp3/recipes/UploadProgress.java:75
if (contentLength != -1) {
System.out.format("%d%% done\n", (100 * bytesWritten) / contentLength);
}
}
}
};
RequestBody requestBody = RequestBody.create(
new File("docs/images/logo-square.png"),
MEDIA_TYPE_PNG);
Request request = new Request.Builder()
.header("Authorization", "Client-ID " + IMGUR_CLIENT_ID)
.url("https://api.imgur.com/3/image")
.post(new ProgressRequestBody(requestBody, progressListener))
.build();
Response response = client.newCall(request).execute();
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
System.out.println(response.body().string());
}
public static void main(String... args) throws Exception {
new UploadProgress().run();
}
private static class ProgressRequestBody extends RequestBody {
private final ProgressListener progressListener;
private final RequestBody delegate;
public ProgressRequestBody(RequestBody delegate, ProgressListener progressListener) {
this.delegate = delegate;
this.progressListener = progressListener;
}
View on GitHub (pinned to 4fc0831380)
Solutions
- Register an Imgur application at https://api.imgur.com/oauth2/addclient and replace IMGUR_CLIENT_ID with your own Client-ID.
- Inspect response.code(), response.header('X-RateLimit-ClientRemaining'), and response.body().string() to differentiate 401/403/429/400.
- Verify the file exists before building the request: java.nio.file.Files.exists(Path.of("docs/images/logo-square.png")) — a missing file throws FileNotFoundException, not this error.
- If running many uploads, sleep based on X-RateLimit-Userreset to stay under the Imgur quota and avoid 429.
Example fix
// before
Response response = client.newCall(request).execute();
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
System.out.println(response.body().string());
// after
try (Response response = client.newCall(request).execute()) {
if (!response.isSuccessful()) {
throw new IOException("Imgur upload failed: HTTP " + response.code()
+ " remaining=" + response.header("X-RateLimit-ClientRemaining")
+ " body=" + response.peekBody(1024).string());
}
System.out.println(response.body().string());
} Defensive patterns
Strategy: validation
Validate before calling
java.nio.file.Path image = java.nio.file.Paths.get("docs/images/logo-square.png");
if (!java.nio.file.Files.exists(image)) {
throw new java.io.FileNotFoundException(image.toString());
}
String clientId = System.getenv("IMGUR_CLIENT_ID");
if (clientId == null || clientId.isBlank()) {
throw new IllegalStateException("IMGUR_CLIENT_ID env var not set");
}
// Build the request only after both guards pass.
Try / catch
try (Response response = client.newCall(request).execute()) {
switch (response.code()) {
case 401, 403 -> throw new IOException("Imgur auth failed (" + response.code()
+ "); check Client-ID");
case 429 -> throw new IOException("Imgur rate limited; reset at "
+ response.header("X-RateLimit-Userreset"));
}
if (!response.isSuccessful()) {
throw new IOException("Imgur " + response.code() + ": " + response.peekBody(1024).string());
}
handle(response.body().string());
} Prevention
- Register your own Imgur application; the sample Client-ID is widely revoked.
- Verify the upload file exists on disk before constructing RequestBody.create.
- Track X-RateLimit-ClientRemaining and back off before 429.
- Use try-with-resources on Response (the recipe at line 74 does not) to avoid connection leaks on failure.
When it happens
Trigger: Imgur returns 401/403 when the Client-ID is unknown/revoked; 429 when the application exceeds the per-client rate limit; 400 when the uploaded PNG is rejected (corrupt/oversized) or when docs/images/logo-square.png is missing (the RequestBody.create at line 64 throws FileNotFoundException before reaching the network). Imgur's migration to requiring registered apps (post-2020) makes the legacy anonymous Client-ID invalid, yielding 403.
Common situations: Reusing the sample's Client-ID after Imgur revoked anonymous upload access; running the recipe from a directory that does not contain docs/images/logo-square.png; hitting Imgur's per-IP or per-app post quota in a CI loop; uploading from a country Imgur geo-blocks.
Related errors
AI-assisted analysis of square/okhttp@4fc0831380 (2026-08-04).
Data as JSON: /data/errors/4368d499451ca672.json.
Report an issue: GitHub.