{"record":{"id":"86751ab560a219f0","repo":"square/okhttp","slug":"unexpected-code-86751a","errorCode":null,"errorMessage":"Unexpected code ","messagePattern":"Unexpected code ","errorType":"exception","errorClass":"IOException","httpStatus":null,"severity":"error","filePath":"samples/guide/src/main/java/okhttp3/recipes/Authenticate.java","lineNumber":50,"sourceCode":"          }\n\n          System.out.println(\"Authenticating for response: \" + response);\n          System.out.println(\"Challenges: \" + response.challenges());\n          String credential = Credentials.basic(\"jesse\", \"password1\");\n          return response.request().newBuilder()\n              .header(\"Authorization\", credential)\n              .build();\n        })\n        .build();\n  }\n\n  public void run() throws Exception {\n    Request request = new Request.Builder()\n        .url(\"http://publicobject.com/secrets/hellosecret.txt\")\n        .build();\n\n    try (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\n  public static void main(String... args) throws Exception {\n    new Authenticate().run();\n  }\n}\n","sourceCodeStart":32,"sourceCodeEnd":60,"githubUrl":"https://github.com/square/okhttp/blob/91a8b34c6f44bd28c421364f8edadc9f324dddd9/samples/guide/src/main/java/okhttp3/recipes/Authenticate.java#L32-L60","documentation":"Thrown after the configured Authenticator runs: `if (!response.isSuccessful()) throw new IOException(\"Unexpected code \" + response)`. The authenticator adds Basic credentials when the server issues a 401 challenge. If auth succeeds the final response is 2xx; if it fails (wrong credentials, the server still returns 401/403), response.isSuccessful() is false and this throws. The authenticator itself bails out (returns null) if it already tried once.","triggerScenarios":"Credentials.basic(\"jesse\", \"password1\") do not match the protected resource, so publicobject.com reponds 401 a second time; the resource path /secrets/hellosecret.txt was removed and returns 404; the server uses a non-Basic scheme the authenticator does not satisfy; the host no longer requires auth and returns a redirect.","commonSituations":"Using the literal sample credentials against a live server; the secret file was deleted; the server switched to digest/OAuth; copy-pasting the sample without changing username/password to real values.","solutions":["Replace \"jesse\"/\"password1\" with valid credentials for the resource you are actually hitting.","Log response.code() and response.challenges() (as the sample already does) to see the auth scheme and status.","Confirm the protected path still exists; 404 is not an auth failure.","If the server uses a non-Basic scheme, implement an Authenticator that handles that scheme or returns null to stop."],"exampleFix":"// before\nString credential = Credentials.basic(\"jesse\", \"password1\");\n...\nif (!response.isSuccessful()) throw new IOException(\"Unexpected code \" + response);\n\n// after\nString credential = Credentials.basic(realUser, realPassword);\n...\nif (response.code() == 401 || response.code() == 403) {\n  throw new IOException(\"Authentication failed (\" + response.code() + \")\");\n}\nif (!response.isSuccessful()) throw new IOException(\"HTTP \" + response.code());","handlingStrategy":"try-catch","validationCode":"// Inspect challenges + code before trusting the response.\nif (response.code() == 401) {\n  List<Challenge> challenges = response.challenges();\n  // If Basic is not among them, the authenticator cannot help.\n}","typeGuard":"static boolean authenticated(Response r) { return r.code() != 401 && r.code() != 403; }","tryCatchPattern":"try {\n  // call\n} catch (IOException e) {\n  if (e.getMessage().contains(\"Unexpected code\")) {\n    // auth or status failure from the recipe guard; re-auth or surface to user\n  }\n}","preventionTips":["Do not hardcode sample credentials; load real credentials from config/secrets.","Check response.challenges() to confirm the server uses Basic auth.","Return null from your Authenticator to stop infinite retry loops.","Distinguish 401 (auth) from 404 (missing resource)."],"tags":["okhttp","http-status","authentication","basic-auth","java"],"backgroundTag":null,"analyzedSha":"91a8b34c6f44bd28c421364f8edadc9f324dddd9","analyzedAt":"2026-08-10T18:39:54.316Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}