{"record":{"id":"4368d499451ca672","repo":"square/okhttp","slug":"unexpected-code-4368d4","errorCode":null,"errorMessage":"Unexpected code ","messagePattern":"Unexpected code ","errorType":"exception","errorClass":"IOException","httpStatus":null,"severity":"error","filePath":"samples/guide/src/main/java/okhttp3/recipes/UploadProgress.java","lineNumber":75,"sourceCode":"          if (contentLength != -1) {\n            System.out.format(\"%d%% done\\n\", (100 * bytesWritten) / contentLength);\n          }\n        }\n      }\n    };\n\n    RequestBody requestBody = RequestBody.create(\n      new File(\"docs/images/logo-square.png\"),\n      MEDIA_TYPE_PNG);\n\n    Request request = new Request.Builder()\n      .header(\"Authorization\", \"Client-ID \" + IMGUR_CLIENT_ID)\n      .url(\"https://api.imgur.com/3/image\")\n      .post(new ProgressRequestBody(requestBody, progressListener))\n      .build();\n\n    Response response = client.newCall(request).execute();\n    if (!response.isSuccessful()) throw new IOException(\"Unexpected code \" + response);\n\n    System.out.println(response.body().string());\n  }\n\n  public static void main(String... args) throws Exception {\n    new UploadProgress().run();\n  }\n\n  private static class ProgressRequestBody extends RequestBody {\n\n    private final ProgressListener progressListener;\n    private final RequestBody delegate;\n\n    public ProgressRequestBody(RequestBody delegate, ProgressListener progressListener) {\n      this.delegate = delegate;\n      this.progressListener = progressListener;\n    }\n","sourceCodeStart":57,"sourceCodeEnd":93,"githubUrl":"https://github.com/square/okhttp/blob/91a8b34c6f44bd28c421364f8edadc9f324dddd9/samples/guide/src/main/java/okhttp3/recipes/UploadProgress.java#L57-L93","documentation":"Same idiom, this time in the UploadProgress recipe after uploading a PNG to Imgur: `if (!response.isSuccessful()) throw new IOException(\"Unexpected code \" + response);`. The `response` object's toString carries the Imgur error code/message. The wrapping `ProgressRequestBody` only instruments bytes written; it does not change success semantics.","triggerScenarios":"POST to `https://api.imgur.com/3/image` with `Authorization: Client-ID 9199fdef135c122` (a sample/revoked credential) returns 401/403 because Imgur now requires per-application registration and has retired widely-shared demo client IDs. Also fires on 429 (Imgur rate limits, ~12,500/day per app, 50/min anonymous), 400 (missing/malformed multipart body or unsupported media), or 404 if the endpoint path changes.","commonSituations":"Running the recipe as-is with the leaked `IMGUR_CLIENT_ID`; registering an Imgur app but forgetting to pass the new client ID; file `docs/images/logo-square.png` missing or unreadable so the body is empty (server returns 400); Imgur migrating endpoint versions; Imgur blocking uploads from cloud/datacenter IPs.","solutions":["Register at https://api.imgur.com/oauth2/addclient and replace `IMGUR_CLIENT_ID` with your own; for user-scoped uploads use OAuth2 `Bearer <access_token>` instead of `Client-ID`.","Verify the upload file exists and is a valid PNG before building the request (guard against empty/malformed body that yields 400).","Before throwing, read and log `response.body().string()` and `response.code()` so you can tell 401 (auth) from 429 (rate) from 400 (payload).","Respect `X-RateLimit-ClientRemaining`/`X-RateLimit-UserRemaining` headers and back off on 429."],"exampleFix":"// before\nResponse response = client.newCall(request).execute();\nif (!response.isSuccessful()) throw new IOException(\"Unexpected code \" + response);\nSystem.out.println(response.body().string());\n\n// after\ntry (Response response = client.newCall(request).execute()) {\n  String body = response.body() != null ? response.body().string() : \"\";\n  if (!response.isSuccessful()) {\n    throw new IOException(\"Imgur upload failed: HTTP \" + response.code()\n        + \" (rateLimit-client=\" + response.header(\"X-RateLimit-ClientRemaining\") + \"): \" + body);\n  }\n  System.out.println(body);\n}","handlingStrategy":"validation","validationCode":"// Pre-flight: validate credentials and file before the upload.\nString clientId = System.getenv(\"IMGUR_CLIENT_ID\");\nif (clientId == null || clientId.isBlank()) {\n  throw new IllegalStateException(\"IMGUR_CLIENT_ID env var not set.\");\n}\nFile file = new File(\"docs/images/logo-square.png\");\nif (!file.isFile() || file.length() == 0) {\n  throw new IllegalArgumentException(\"Missing or empty upload file: \" + file);\n}\nRequestBody requestBody = RequestBody.create(file, MEDIA_TYPE_PNG);\nRequest request = new Request.Builder()\n    .header(\"Authorization\", \"Client-ID \" + clientId)\n    .url(\"https://api.imgur.com/3/image\")\n    .post(new ProgressRequestBody(requestBody, progressListener))\n    .build();\n\n// Post-call: classify Imgur-specific status.\ntry (Response response = client.newCall(request).execute()) {\n  String body = response.body() != null ? response.body().string() : \"\";\n  if (response.code() == 401 || response.code() == 403) {\n    throw new AuthException(\"Imgur rejected Client-ID (\" + response.code() + \"): \" + body);\n  }\n  if (response.code() == 429) {\n    throw new RateLimitedException(response.header(\"X-RateLimit-UserReset\"));\n  }\n  if (!response.isSuccessful()) throw new IOException(\"Imgur \" + response.code() + \": \" + body);\n}","typeGuard":"private static boolean imgurAuthFailed(Response r) {\n  return r.code() == 401 || r.code() == 403;\n}\nprivate static boolean imgurRateLimited(Response r) {\n  return r.code() == 429\n      || \"0\".equals(r.header(\"X-RateLimit-UserRemaining\"));\n}","tryCatchPattern":"try (Response response = client.newCall(request).execute()) {\n  String body = response.body() != null ? response.body().string() : \"\";\n  if (imgurAuthFailed(response)) {\n    throw new AuthException(\"Imgur auth failed (\" + response.code() + \"): \" + body);\n  }\n  if (imgurRateLimited(response)) {\n    throw new RateLimitedException(response.header(\"X-RateLimit-UserReset\"));\n  }\n  if (!response.isSuccessful()) {\n    throw new IOException(\"Imgur upload failed: HTTP \" + response.code() + \": \" + body);\n  }\n  System.out.println(body);\n} catch (RateLimitedException e) {\n  sleepUntil(e.resetEpoch()); // then optionally retry\n} catch (AuthException e) {\n  // surface to operator — credentials must be rotated manually\n  throw e;\n}","preventionTips":["Never ship shared sample credentials like `IMGUR_CLIENT_ID = \"9199fdef135c122\"`; register your own app.","Verify the upload file exists and is non-empty before constructing the RequestBody (avoids spurious 400s).","Always read the response body even on error — Imgur returns a JSON error message you need.","Track Imgur rate-limit headers (`X-RateLimit-ClientRemaining`, `X-RateLimit-UserRemaining`) and back off proactively."],"tags":["okhttp","java","http-status","imgur","authentication","rate-limit"],"backgroundTag":null,"analyzedSha":"91a8b34c6f44bd28c421364f8edadc9f324dddd9","analyzedAt":"2026-08-10T18:39:54.316Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}