{"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/4fc083138014aba3d0078f5c26d1ce84815fa984/samples/guide/src/main/java/okhttp3/recipes/UploadProgress.java#L57-L93","documentation":"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.","triggerScenarios":"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.","commonSituations":"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.","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."],"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  if (!response.isSuccessful()) {\n    throw new IOException(\"Imgur upload failed: HTTP \" + response.code()\n        + \" remaining=\" + response.header(\"X-RateLimit-ClientRemaining\")\n        + \" body=\" + response.peekBody(1024).string());\n  }\n  System.out.println(response.body().string());\n}","handlingStrategy":"validation","validationCode":"java.nio.file.Path image = java.nio.file.Paths.get(\"docs/images/logo-square.png\");\nif (!java.nio.file.Files.exists(image)) {\n  throw new java.io.FileNotFoundException(image.toString());\n}\nString clientId = System.getenv(\"IMGUR_CLIENT_ID\");\nif (clientId == null || clientId.isBlank()) {\n  throw new IllegalStateException(\"IMGUR_CLIENT_ID env var not set\");\n}\n// Build the request only after both guards pass.\n","typeGuard":null,"tryCatchPattern":"try (Response response = client.newCall(request).execute()) {\n  switch (response.code()) {\n    case 401, 403 -> throw new IOException(\"Imgur auth failed (\" + response.code()\n        + \"); check Client-ID\");\n    case 429 -> throw new IOException(\"Imgur rate limited; reset at \"\n        + response.header(\"X-RateLimit-Userreset\"));\n  }\n  if (!response.isSuccessful()) {\n    throw new IOException(\"Imgur \" + response.code() + \": \" + response.peekBody(1024).string());\n  }\n  handle(response.body().string());\n}","preventionTips":["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."],"tags":["okhttp","java","imgur-api","http-status","authentication","rate-limiting","file-upload"],"analyzedSha":"4fc083138014aba3d0078f5c26d1ce84815fa984","analyzedAt":"2026-08-04T19:09:04.639Z","schemaVersion":2}